common.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "image"
  14. "image/png"
  15. "io"
  16. "math"
  17. "math/rand"
  18. "net"
  19. "net/http"
  20. "os"
  21. "os/exec"
  22. "path"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/shopspring/decimal"
  28. )
  29. // 随机数种子
  30. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  31. func GetRandString(size int) string {
  32. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", "@", "#", "$", "%", "^", "&", "*"}
  33. randomSb := ""
  34. digitSize := len(allLetterDigit)
  35. for i := 0; i < size; i++ {
  36. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  37. }
  38. return randomSb
  39. }
  40. func GetRandStringNoSpecialChar(size int) string {
  41. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
  42. randomSb := ""
  43. digitSize := len(allLetterDigit)
  44. for i := 0; i < size; i++ {
  45. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  46. }
  47. return randomSb
  48. }
  49. func StringsToJSON(str string) string {
  50. rs := []rune(str)
  51. jsons := ""
  52. for _, r := range rs {
  53. rint := int(r)
  54. if rint < 128 {
  55. jsons += string(r)
  56. } else {
  57. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  58. }
  59. }
  60. return jsons
  61. }
  62. // 序列化
  63. func ToString(v interface{}) string {
  64. data, _ := json.Marshal(v)
  65. return string(data)
  66. }
  67. // md5加密
  68. func MD5(data string) string {
  69. m := md5.Sum([]byte(data))
  70. return hex.EncodeToString(m[:])
  71. }
  72. // 获取数字随机字符
  73. func GetRandDigit(n int) string {
  74. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  75. }
  76. // 获取随机数
  77. func GetRandNumber(n int) int {
  78. return rnd.Intn(n)
  79. }
  80. func GetRandInt(min, max int) int {
  81. if min >= max || min == 0 || max == 0 {
  82. return max
  83. }
  84. return rand.Intn(max-min) + min
  85. }
  86. func GetToday(format string) string {
  87. today := time.Now().Format(format)
  88. return today
  89. }
  90. // 获取今天剩余秒数
  91. func GetTodayLastSecond() time.Duration {
  92. today := GetToday(FormatDate) + " 23:59:59"
  93. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  94. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  95. }
  96. // 处理出生日期函数
  97. func GetBrithDate(idcard string) string {
  98. l := len(idcard)
  99. var s string
  100. if l == 15 {
  101. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  102. return s
  103. }
  104. if l == 18 {
  105. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  106. return s
  107. }
  108. return GetToday(FormatDate)
  109. }
  110. // 处理性别
  111. func WhichSexByIdcard(idcard string) string {
  112. var sexs = [2]string{"女", "男"}
  113. length := len(idcard)
  114. if length == 18 {
  115. sex, _ := strconv.Atoi(string(idcard[16]))
  116. return sexs[sex%2]
  117. } else if length == 15 {
  118. sex, _ := strconv.Atoi(string(idcard[14]))
  119. return sexs[sex%2]
  120. }
  121. return "男"
  122. }
  123. // 截取小数点后几位
  124. func SubFloatToString(f float64, m int) string {
  125. n := strconv.FormatFloat(f, 'f', -1, 64)
  126. if n == "" {
  127. return ""
  128. }
  129. if m >= len(n) {
  130. return n
  131. }
  132. newn := strings.Split(n, ".")
  133. if m == 0 {
  134. return newn[0]
  135. }
  136. if len(newn) < 2 || m >= len(newn[1]) {
  137. return n
  138. }
  139. return newn[0] + "." + newn[1][:m]
  140. }
  141. // 截取小数点后几位
  142. func SubFloatToFloat(f float64, m int) float64 {
  143. newn := SubFloatToString(f, m)
  144. newf, _ := strconv.ParseFloat(newn, 64)
  145. return newf
  146. }
  147. // 截取小数点后几位
  148. func SubFloatToFloatStr(f float64, m int) string {
  149. newn := SubFloatToString(f, m)
  150. return newn
  151. }
  152. // 获取相差时间-年
  153. func GetYearDiffer(start_time, end_time string) int {
  154. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  155. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  156. age := t2.Year() - t1.Year()
  157. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  158. age--
  159. }
  160. return age
  161. }
  162. // 获取相差时间-秒
  163. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  164. diff := end_time.Unix() - start_time.Unix()
  165. return diff
  166. }
  167. func FixFloat(f float64, m int) float64 {
  168. newn := SubFloatToString(f+0.00000001, m)
  169. newf, _ := strconv.ParseFloat(newn, 64)
  170. return newf
  171. }
  172. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  173. func StrListToString(strList []string) (str string) {
  174. if len(strList) > 0 {
  175. for k, v := range strList {
  176. if k == 0 {
  177. str = v
  178. } else {
  179. str = str + "," + v
  180. }
  181. }
  182. return
  183. }
  184. return ""
  185. }
  186. // 数据没有记录
  187. func ErrNoRow() string {
  188. return "<QuerySeter> no row found"
  189. }
  190. // 校验邮箱格式
  191. func ValidateEmailFormatat(email string) bool {
  192. reg := regexp.MustCompile(RegularEmail)
  193. return reg.MatchString(email)
  194. }
  195. // 验证是否是手机号
  196. func ValidateMobileFormatat(mobileNum string) bool {
  197. reg := regexp.MustCompile(RegularMobile)
  198. return reg.MatchString(mobileNum)
  199. }
  200. // 判断文件是否存在
  201. func FileIsExist(filePath string) bool {
  202. _, err := os.Stat(filePath)
  203. return err == nil || os.IsExist(err)
  204. }
  205. // 获取图片扩展名
  206. func GetImgExt(file string) (ext string, err error) {
  207. var headerByte []byte
  208. headerByte = make([]byte, 8)
  209. fd, err := os.Open(file)
  210. if err != nil {
  211. return "", err
  212. }
  213. defer fd.Close()
  214. _, err = fd.Read(headerByte)
  215. if err != nil {
  216. return "", err
  217. }
  218. xStr := fmt.Sprintf("%x", headerByte)
  219. switch {
  220. case xStr == "89504e470d0a1a0a":
  221. ext = ".png"
  222. case xStr == "0000010001002020":
  223. ext = ".ico"
  224. case xStr == "0000020001002020":
  225. ext = ".cur"
  226. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  227. ext = ".gif"
  228. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  229. ext = ".tga"
  230. case xStr[:8] == "464f524d":
  231. ext = ".iff"
  232. case xStr[:8] == "52494646":
  233. ext = ".ani"
  234. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  235. ext = ".tiff"
  236. case xStr[:4] == "424d":
  237. ext = ".bmp"
  238. case xStr[:4] == "ffd8":
  239. ext = ".jpg"
  240. case xStr[:2] == "0a":
  241. ext = ".pcx"
  242. default:
  243. ext = ""
  244. }
  245. return ext, nil
  246. }
  247. // 保存图片
  248. func SaveImage(path string, img image.Image) (err error) {
  249. //需要保持的文件
  250. imgfile, err := os.Create(path)
  251. defer imgfile.Close()
  252. // 以PNG格式保存文件
  253. err = png.Encode(imgfile, img)
  254. return err
  255. }
  256. // 下载图片
  257. func DownloadImage(imgUrl string) (filePath string, err error) {
  258. imgPath := "./static/imgs/"
  259. fileName := path.Base(imgUrl)
  260. res, err := http.Get(imgUrl)
  261. if err != nil {
  262. fmt.Println("A error occurred!")
  263. return
  264. }
  265. defer res.Body.Close()
  266. // 获得get请求响应的reader对象
  267. reader := bufio.NewReaderSize(res.Body, 32*1024)
  268. filePath = imgPath + fileName
  269. file, err := os.Create(filePath)
  270. if err != nil {
  271. return
  272. }
  273. // 获得文件的writer对象
  274. writer := bufio.NewWriter(file)
  275. written, _ := io.Copy(writer, reader)
  276. fmt.Printf("Total length: %d \n", written)
  277. return
  278. }
  279. // 保存base64数据为文件
  280. func SaveBase64ToFile(content, path string) error {
  281. data, err := base64.StdEncoding.DecodeString(content)
  282. if err != nil {
  283. return err
  284. }
  285. f, err := os.Create(path)
  286. defer f.Close()
  287. if err != nil {
  288. return err
  289. }
  290. f.Write(data)
  291. return nil
  292. }
  293. func SaveBase64ToFileBySeek(content, path string) (err error) {
  294. data, err := base64.StdEncoding.DecodeString(content)
  295. exist, err := PathExists(path)
  296. if err != nil {
  297. return
  298. }
  299. if !exist {
  300. f, err := os.Create(path)
  301. if err != nil {
  302. return err
  303. }
  304. n, _ := f.Seek(0, 2)
  305. // 从末尾的偏移量开始写入内容
  306. _, err = f.WriteAt([]byte(data), n)
  307. defer f.Close()
  308. } else {
  309. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  310. if err != nil {
  311. return err
  312. }
  313. n, _ := f.Seek(0, 2)
  314. // 从末尾的偏移量开始写入内容
  315. _, err = f.WriteAt([]byte(data), n)
  316. defer f.Close()
  317. }
  318. return nil
  319. }
  320. func PathExists(path string) (bool, error) {
  321. _, err := os.Stat(path)
  322. if err == nil {
  323. return true, nil
  324. }
  325. if os.IsNotExist(err) {
  326. return false, nil
  327. }
  328. return false, err
  329. }
  330. func StartIndex(page, pagesize int) int {
  331. if page > 1 {
  332. return (page - 1) * pagesize
  333. }
  334. return 0
  335. }
  336. func PageCount(count, pagesize int) int {
  337. if count%pagesize > 0 {
  338. return count/pagesize + 1
  339. } else {
  340. return count / pagesize
  341. }
  342. }
  343. func TrimHtml(src string) string {
  344. //将HTML标签全转换成小写
  345. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  346. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  347. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  348. src = re.ReplaceAllString(src, "[图片]")
  349. re, _ = regexp.Compile("class[\\S\\s]+?>")
  350. src = re.ReplaceAllString(src, "")
  351. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  352. src = re.ReplaceAllString(src, "")
  353. return strings.TrimSpace(src)
  354. }
  355. //1556164246 -> 2019-04-25 03:50:46 +0000
  356. //timestamp
  357. func TimeToTimestamp() {
  358. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  359. }
  360. func ToUnicode(text string) string {
  361. textQuoted := strconv.QuoteToASCII(text)
  362. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  363. return textUnquoted
  364. }
  365. func VersionToInt(version string) int {
  366. version = strings.Replace(version, ".", "", -1)
  367. n, _ := strconv.Atoi(version)
  368. return n
  369. }
  370. func IsCheckInList(list []int, s int) bool {
  371. for _, v := range list {
  372. if v == s {
  373. return true
  374. }
  375. }
  376. return false
  377. }
  378. func round(num float64) int {
  379. return int(num + math.Copysign(0.5, num))
  380. }
  381. func toFixed(num float64, precision int) float64 {
  382. output := math.Pow(10, float64(precision))
  383. return float64(round(num*output)) / output
  384. }
  385. // GetWilsonScore returns Wilson Score
  386. func GetWilsonScore(p, n float64) float64 {
  387. if p == 0 && n == 0 {
  388. return 0
  389. }
  390. return toFixed(((p+1.9208)/(p+n)-1.96*math.Sqrt(p*n/(p+n)+0.9604)/(p+n))/(1+3.8416/(p+n)), 2)
  391. }
  392. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  393. func ChangeWordsToNum(str string) (numStr string) {
  394. words := ([]rune)(str)
  395. num := 0
  396. n := 0
  397. for i := 0; i < len(words); i++ {
  398. word := string(words[i : i+1])
  399. switch word {
  400. case "万":
  401. if n == 0 {
  402. n = 1
  403. }
  404. n = n * 10000
  405. num = num*10000 + n
  406. n = 0
  407. case "千":
  408. if n == 0 {
  409. n = 1
  410. }
  411. n = n * 1000
  412. num += n
  413. n = 0
  414. case "百":
  415. if n == 0 {
  416. n = 1
  417. }
  418. n = n * 100
  419. num += n
  420. n = 0
  421. case "十":
  422. if n == 0 {
  423. n = 1
  424. }
  425. n = n * 10
  426. num += n
  427. n = 0
  428. case "一":
  429. n += 1
  430. case "二":
  431. n += 2
  432. case "三":
  433. n += 3
  434. case "四":
  435. n += 4
  436. case "五":
  437. n += 5
  438. case "六":
  439. n += 6
  440. case "七":
  441. n += 7
  442. case "八":
  443. n += 8
  444. case "九":
  445. n += 9
  446. case "零":
  447. default:
  448. if n > 0 {
  449. num += n
  450. n = 0
  451. }
  452. if num == 0 {
  453. numStr += word
  454. } else {
  455. numStr += strconv.Itoa(num) + word
  456. num = 0
  457. }
  458. }
  459. }
  460. if n > 0 {
  461. num += n
  462. n = 0
  463. }
  464. if num != 0 {
  465. numStr += strconv.Itoa(num)
  466. }
  467. return
  468. }
  469. func Sha1(data string) string {
  470. sha1 := sha1.New()
  471. sha1.Write([]byte(data))
  472. return hex.EncodeToString(sha1.Sum([]byte("")))
  473. }
  474. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  475. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  476. out, err := exec.Command("bash", "-c", cmd).Output()
  477. if err != nil {
  478. return
  479. }
  480. outTimes := string(out)
  481. fmt.Println("outTimes:", outTimes)
  482. if outTimes != "" {
  483. timeArr := strings.Split(outTimes, ":")
  484. h := timeArr[0]
  485. m := timeArr[1]
  486. s := timeArr[2]
  487. hInt, err := strconv.Atoi(h)
  488. if err != nil {
  489. return playSeconds, err
  490. }
  491. mInt, err := strconv.Atoi(m)
  492. if err != nil {
  493. return playSeconds, err
  494. }
  495. s = strings.Trim(s, " ")
  496. s = strings.Trim(s, "\n")
  497. sInt, err := strconv.ParseFloat(s, 64)
  498. if err != nil {
  499. return playSeconds, err
  500. }
  501. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  502. }
  503. return
  504. }
  505. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  506. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  507. tradeCode = strings.Trim(tradeCode, " ")
  508. tradeCodeInt, err := strconv.Atoi(tradeCode)
  509. if err != nil {
  510. return
  511. }
  512. tradeCodeInt = tradeCodeInt + 1
  513. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  514. return
  515. }
  516. // excel日期字段格式化 yyyy-mm-dd
  517. func ConvertToFormatDay(excelDaysString string) string {
  518. // 2006-01-02 距离 1900-01-01的天数
  519. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  520. curDiffDay := excelDaysString
  521. b, _ := strconv.Atoi(curDiffDay)
  522. // 获取excel的日期距离2006-01-02的天数
  523. realDiffDay := b - baseDiffDay
  524. //fmt.Println("realDiffDay:",realDiffDay)
  525. // 距离2006-01-02 秒数
  526. realDiffSecond := realDiffDay * 24 * 3600
  527. //fmt.Println("realDiffSecond:",realDiffSecond)
  528. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  529. baseOriginSecond := 1136185445
  530. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  531. return resultTime
  532. }
  533. func CheckPwd(pwd string) bool {
  534. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  535. reg := regexp.MustCompile(compile)
  536. flag := reg.MatchString(pwd)
  537. return flag
  538. }
  539. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  540. // 数字月份必须前置补零
  541. if len(myMonth) == 1 {
  542. myMonth = "0" + myMonth
  543. }
  544. yInt, _ := strconv.Atoi(myYear)
  545. timeLayout := "2006-01-02 15:04:05"
  546. loc, _ := time.LoadLocation("Local")
  547. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  548. newMonth := theTime.Month()
  549. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  550. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  551. return t1, t2
  552. }
  553. // 移除字符串中的空格
  554. func TrimStr(str string) (str2 string) {
  555. return strings.Replace(str, " ", "", -1)
  556. }
  557. // 字符串转换为time
  558. func StrTimeToTime(strTime string) time.Time {
  559. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  560. loc, _ := time.LoadLocation("Local") //重要:获取时区
  561. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  562. return resultTime
  563. }
  564. // GetOrmInReplace 获取orm的in查询替换?的方法
  565. func GetOrmInReplace(num int) string {
  566. template := make([]string, num)
  567. for i := 0; i < num; i++ {
  568. template[i] = "?"
  569. }
  570. return strings.Join(template, ",")
  571. }
  572. // RevSlice 反转切片
  573. func RevSlice(slice []int) []int {
  574. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  575. slice[i], slice[j] = slice[j], slice[i]
  576. }
  577. return slice
  578. }
  579. // GetTimeSubDay 计算两个时间的自然日期差
  580. func GetTimeSubDay(t1, t2 time.Time) int {
  581. var day int
  582. swap := false
  583. if t1.Unix() > t2.Unix() {
  584. t1, t2 = t2, t1
  585. swap = true
  586. }
  587. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  588. day = int(t2.Sub(t1).Hours() / 24)
  589. // 计算在t1+两个时间的余数之后天数是否有变化
  590. if t1_.Day() != t1.Day() {
  591. day += 1
  592. }
  593. if swap {
  594. day = -day
  595. }
  596. return day
  597. }
  598. // GetDaysBetween2Date 计算两个日期之间相差几天
  599. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  600. // 将字符串转化为Time格式
  601. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  602. if err != nil {
  603. return 0, err
  604. }
  605. // 将字符串转化为Time格式
  606. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  607. if err != nil {
  608. return 0, err
  609. }
  610. //计算相差天数
  611. return int(date1.Sub(date2).Hours() / 24), nil
  612. }
  613. // MapSorter 对于map 排序
  614. type MapSorter []Item
  615. type Item struct {
  616. Key int
  617. Val float64
  618. }
  619. func NewMapSorter(m map[int]float64) MapSorter {
  620. ms := make(MapSorter, 0, len(m))
  621. for k, v := range m {
  622. ms = append(ms, Item{k, v})
  623. }
  624. return ms
  625. }
  626. func (ms MapSorter) Len() int {
  627. return len(ms)
  628. }
  629. func (ms MapSorter) Less(i, j int) bool {
  630. return ms[i].Val > ms[j].Val // 按值排序
  631. //return ms[i].Key < ms[j].Key // 按键排序
  632. }
  633. func (ms MapSorter) Swap(i, j int) {
  634. ms[i], ms[j] = ms[j], ms[i]
  635. }
  636. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  637. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  638. for _, id := range idIntList {
  639. if id == searchId {
  640. has = true
  641. return
  642. }
  643. }
  644. return
  645. }
  646. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  647. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  648. for _, id := range idStrList {
  649. if id == searchId {
  650. has = true
  651. return
  652. }
  653. }
  654. return
  655. }
  656. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  657. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  658. startDate = tmpStartDate
  659. endDate = tmpEndDate
  660. switch dateType {
  661. case 1:
  662. startDate = "2000-01-01"
  663. endDate = ""
  664. case 2:
  665. startDate = "2010-01-01"
  666. endDate = ""
  667. case 3:
  668. startDate = "2015-01-01"
  669. endDate = ""
  670. case 4:
  671. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  672. startDate = "2021-01-01"
  673. endDate = ""
  674. case 5:
  675. //startDate = startDate + "-01"
  676. //endDate = endDate + "-01"
  677. case 6:
  678. //startDate = startDate + "-01"
  679. endDate = ""
  680. case 7:
  681. startDate = "2018-01-01"
  682. endDate = ""
  683. case 8:
  684. startDate = "2019-01-01"
  685. endDate = ""
  686. case 9:
  687. startDate = "2020-01-01"
  688. endDate = ""
  689. case 11:
  690. startDate = "2022-01-01"
  691. endDate = ""
  692. }
  693. // 兼容日期错误
  694. {
  695. if strings.Count(startDate, "-") == 1 {
  696. startDate = startDate + "-01"
  697. }
  698. if strings.Count(endDate, "-") == 1 {
  699. endDate = endDate + "-01"
  700. }
  701. }
  702. return
  703. }
  704. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  705. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  706. switch dateType {
  707. case 1:
  708. startDate = currDate.AddDate(0, -3, 0)
  709. case 2:
  710. startDate = currDate.AddDate(0, -6, 0)
  711. case 3:
  712. startDate = currDate.AddDate(-1, 0, 0)
  713. case 4:
  714. startDate = currDate.AddDate(-2, 0, 0)
  715. case 5:
  716. startDate = currDate.AddDate(-3, 0, 0)
  717. case 6:
  718. startDate = currDate.AddDate(-5, 0, 0)
  719. case 7:
  720. startDate = currDate.AddDate(-10, 0, 0)
  721. }
  722. return
  723. }
  724. // GetCeilNewNum 保留n位有效数字的向上取整
  725. // @params num 实际数据
  726. // @params baseLen 需要保留的有效位数
  727. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  728. if num >= 1 {
  729. tmpNum := int(math.Ceil(num)) // 向上取整
  730. str := strconv.Itoa(tmpNum)
  731. lenStr := len(str)
  732. if lenStr > baseLen {
  733. newNumStr := str[0:baseLen]
  734. newNumInt, _ := strconv.Atoi(newNumStr)
  735. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  736. if newNum < num {
  737. newNumInt += 1
  738. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  739. }
  740. } else {
  741. newNum = float64(tmpNum)
  742. }
  743. return
  744. } else if num > 0 {
  745. // 这是小数
  746. str := strconv.FormatFloat(num, 'f', -1, 64)
  747. // 去除小数点和负号
  748. str = removeDecimalPoint(str)
  749. // 计算字符串长度
  750. lenStr := len(str)
  751. if lenStr > baseLen {
  752. newNumStr := str[0:baseLen]
  753. newNumInt, _ := strconv.Atoi(newNumStr)
  754. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  755. if newNum < num {
  756. newNumInt += 1
  757. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  758. }
  759. } else {
  760. newNum = num
  761. }
  762. } else if num > -1 {
  763. // 这是小数
  764. str := strconv.FormatFloat(num, 'f', -1, 64)
  765. // 去除小数点和负号
  766. str = removeDecimalPoint(str)
  767. // 计算字符串长度
  768. lenStr := len(str)
  769. if lenStr > baseLen {
  770. newNumStr := str[0:baseLen]
  771. newNumInt, _ := strconv.Atoi(newNumStr)
  772. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  773. newNum = -newNum
  774. if newNum < num {
  775. newNumInt -= 1
  776. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  777. newNum = -newNum
  778. }
  779. } else {
  780. newNum = num
  781. }
  782. if newNum == -0 {
  783. newNum = 0
  784. }
  785. } else { // 小于等于-1
  786. tmpNumFloat := math.Abs(num)
  787. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  788. str := strconv.Itoa(tmpNum)
  789. lenStr := len(str)
  790. if lenStr > baseLen {
  791. newNumStr := str[0:baseLen]
  792. //fmt.Println("newNumStr:", newNumStr)
  793. newNumInt, _ := strconv.Atoi(newNumStr)
  794. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  795. newNum = -newNum
  796. if newNum < num {
  797. newNumInt -= 1
  798. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  799. newNum = -newNum
  800. }
  801. } else {
  802. newNum = float64(-tmpNum)
  803. }
  804. }
  805. return
  806. }
  807. // GetFloorNewNum 保留n位有效数字的向下取整
  808. // @params num 实际数据
  809. // @params baseLen 需要保留的有效位数
  810. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  811. if num >= 1 {
  812. tmpNum := int(math.Floor(num)) // 向上取整
  813. str := strconv.Itoa(tmpNum)
  814. lenStr := len(str)
  815. if lenStr > baseLen {
  816. newNumStr := str[0:baseLen]
  817. newNumInt, _ := strconv.Atoi(newNumStr)
  818. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  819. if newNum < num {
  820. newNumInt -= 1
  821. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  822. }
  823. } else {
  824. newNum = float64(tmpNum)
  825. }
  826. return
  827. } else if num > 0 {
  828. // 这是小数
  829. str := strconv.FormatFloat(num, 'f', -1, 64)
  830. // 去除小数点和负号
  831. str = removeDecimalPoint(str)
  832. // 计算字符串长度
  833. lenStr := len(str)
  834. if lenStr > baseLen {
  835. newNumStr := str[0:baseLen]
  836. newNumInt, _ := strconv.Atoi(newNumStr)
  837. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  838. if newNum > num {
  839. newNumInt -= 1
  840. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  841. }
  842. } else {
  843. newNum = num
  844. }
  845. } else if num > -1 {
  846. // 这是小数
  847. str := strconv.FormatFloat(num, 'f', -1, 64)
  848. // 去除小数点和负号
  849. str = removeDecimalPoint(str)
  850. // 计算字符串长度
  851. lenStr := len(str)
  852. if lenStr > baseLen {
  853. newNumStr := str[0:baseLen]
  854. newNumInt, _ := strconv.Atoi(newNumStr)
  855. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  856. newNum = -newNum
  857. if newNum > num {
  858. newNumInt += 1
  859. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  860. newNum = -newNum
  861. }
  862. } else {
  863. newNum = num
  864. }
  865. if newNum == -0 {
  866. newNum = 0
  867. }
  868. } else { // 小于等于-1
  869. tmpNumFloat := math.Abs(num)
  870. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  871. str := strconv.Itoa(tmpNum)
  872. lenStr := len(str)
  873. if lenStr > baseLen {
  874. newNumStr := str[0:baseLen]
  875. //fmt.Println("newNumStr:", newNumStr)
  876. newNumInt, _ := strconv.Atoi(newNumStr)
  877. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  878. newNum = -newNum
  879. if newNum > num {
  880. newNumInt += 1
  881. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  882. newNum = -newNum
  883. }
  884. } else {
  885. newNum = float64(-tmpNum)
  886. }
  887. }
  888. return
  889. }
  890. // 去除小数点和负号
  891. func removeDecimalPoint(str string) string {
  892. // 去除小数点
  893. str = str[strings.Index(str, ".")+1:]
  894. return str
  895. }
  896. func GetLocalIP() (ip string, err error) {
  897. addrs, err := net.InterfaceAddrs()
  898. if err != nil {
  899. return
  900. }
  901. for _, addr := range addrs {
  902. ipAddr, ok := addr.(*net.IPNet)
  903. if !ok {
  904. continue
  905. }
  906. if ipAddr.IP.IsLoopback() {
  907. continue
  908. }
  909. if !ipAddr.IP.IsGlobalUnicast() {
  910. continue
  911. }
  912. return ipAddr.IP.String(), nil
  913. }
  914. return
  915. }
  916. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
  917. startDate = tmpStartDate
  918. endDate = tmpEndDate
  919. switch dateType {
  920. case 1:
  921. startDate = "2000-01-01"
  922. endDate = ""
  923. case 2:
  924. startDate = "2010-01-01"
  925. endDate = ""
  926. case 3:
  927. startDate = "2015-01-01"
  928. endDate = ""
  929. case 4:
  930. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  931. startDate = "2021-01-01"
  932. endDate = ""
  933. case 5:
  934. //startDate = startDate + "-01"
  935. //endDate = endDate + "-01"
  936. case 6:
  937. //startDate = startDate + "-01"
  938. endDate = ""
  939. case 7:
  940. startDate = "2018-01-01"
  941. endDate = ""
  942. case 8:
  943. startDate = "2019-01-01"
  944. endDate = ""
  945. case 9:
  946. startDate = "2020-01-01"
  947. endDate = ""
  948. case 11:
  949. startDate = "2022-01-01"
  950. endDate = ""
  951. case DateTypeNYears:
  952. if startYear == 0 { //默认取最近5年
  953. startYear = 5
  954. }
  955. if yearMax == 0 {
  956. return
  957. }
  958. startYear = startYear - 1
  959. baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
  960. startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  961. endDate = ""
  962. }
  963. // 兼容日期错误
  964. {
  965. if strings.Count(startDate, "-") == 1 {
  966. startDate = startDate + "-01"
  967. }
  968. if strings.Count(endDate, "-") == 1 {
  969. endDate = endDate + "-01"
  970. }
  971. }
  972. return
  973. }
  974. func GetColorMap() map[int]string {
  975. colorMap := make(map[int]string)
  976. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  977. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  978. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  979. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  980. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  981. for k, v := range colors {
  982. colorMap[k] = v
  983. }
  984. return colorMap
  985. }
  986. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  987. func GetDaysDiff1900(date string) int {
  988. // 将字符串转换为时间类型
  989. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  990. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  991. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  992. if err != nil {
  993. return 0
  994. }
  995. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  996. if err != nil {
  997. return 0
  998. }
  999. // 计算两个日期之间的天数差值
  1000. duration := tEnd.Sub(tStart).Hours() / 24
  1001. days := int(duration)
  1002. return days
  1003. }
  1004. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  1005. funMap := getFormulaMap()
  1006. for k, v := range funMap {
  1007. formulaStr = strings.Replace(formulaStr, k, v, -1)
  1008. }
  1009. replaceCount := 0
  1010. for tag, val := range valTagMap {
  1011. dvStr := fmt.Sprintf("%v", val)
  1012. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  1013. replaceCount++
  1014. }
  1015. for k, v := range funMap {
  1016. formulaStr = strings.Replace(formulaStr, v, k, -1)
  1017. }
  1018. return formulaStr
  1019. }
  1020. // GetFrequencyEn 获取频度的英文版
  1021. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1022. switch frequency {
  1023. case "日度":
  1024. frequencyEn = "day"
  1025. return
  1026. case "周度":
  1027. frequencyEn = "week"
  1028. return
  1029. case "旬度":
  1030. frequencyEn = "ten days"
  1031. return
  1032. case "月度":
  1033. frequencyEn = "month"
  1034. return
  1035. case "季度":
  1036. frequencyEn = "quarter"
  1037. return
  1038. case "年度":
  1039. frequencyEn = "year"
  1040. return
  1041. }
  1042. return
  1043. }
  1044. // DateConvMysqlConvMongo
  1045. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1046. // @author: Roc
  1047. // @datetime 2024-05-08 11:03:26
  1048. // @param dateCon string
  1049. func DateConvMysqlConvMongo(dateCon string) string {
  1050. cond := ""
  1051. switch dateCon {
  1052. case "=":
  1053. cond = "$eq"
  1054. case "<":
  1055. cond = "$lt"
  1056. case "<=":
  1057. cond = "$lte"
  1058. case ">":
  1059. cond = "$gt"
  1060. case ">=":
  1061. cond = "$gte"
  1062. }
  1063. return cond
  1064. }
  1065. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  1066. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  1067. remain := len(result) % 8
  1068. if remain > 0 {
  1069. mod := 8 - remain
  1070. for i := 0; i < mod; i++ {
  1071. result = append(result, 0)
  1072. }
  1073. }
  1074. origData, err := TripleDesDecrypt(result, []byte(desKey))
  1075. if err != nil {
  1076. panic(any(err))
  1077. }
  1078. return origData
  1079. }
  1080. // // 3DES解密
  1081. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  1082. block, err := des.NewTripleDESCipher(key)
  1083. if err != nil {
  1084. return nil, err
  1085. }
  1086. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  1087. origData := make([]byte, len(crypted))
  1088. // origData := crypted
  1089. blockMode.CryptBlocks(origData, crypted)
  1090. origData = PKCS5UnPadding(origData)
  1091. // origData = ZeroUnPadding(origData)
  1092. return origData, nil
  1093. }
  1094. func PKCS5UnPadding(origData []byte) []byte {
  1095. length := len(origData)
  1096. // 去掉最后一个字节 unpadding 次
  1097. unpadding := int(origData[length-1])
  1098. return origData[:(length - unpadding)]
  1099. }
  1100. func TimeTransferString(format string, t time.Time) string {
  1101. str := t.Format(format)
  1102. if t.IsZero() {
  1103. return ""
  1104. }
  1105. return str
  1106. }
  1107. // handleSystemAppointDateT
  1108. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1109. // @author: Roc
  1110. // @datetime2023-10-27 09:31:35
  1111. // @param Frequency string
  1112. // @param Day string
  1113. // @return date string
  1114. // @return err error
  1115. // @return errMsg string
  1116. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1117. //currDate := time.Now()
  1118. switch frequency {
  1119. case "本周":
  1120. day := int(currDate.Weekday())
  1121. if day == 0 { // 周日
  1122. day = 7
  1123. }
  1124. num := 0
  1125. switch appointDay {
  1126. case "周一":
  1127. num = 1
  1128. case "周二":
  1129. num = 2
  1130. case "周三":
  1131. num = 3
  1132. case "周四":
  1133. num = 4
  1134. case "周五":
  1135. num = 5
  1136. case "周六":
  1137. num = 6
  1138. case "周日":
  1139. num = 7
  1140. }
  1141. day = num - day
  1142. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1143. case "本旬":
  1144. day := currDate.Day()
  1145. var tmpDate time.Time
  1146. switch appointDay {
  1147. case "第一天":
  1148. if day <= 10 {
  1149. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1150. } else if day <= 20 {
  1151. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1152. } else {
  1153. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1154. }
  1155. case "最后一天":
  1156. if day <= 10 {
  1157. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1158. } else if day <= 20 {
  1159. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1160. } else {
  1161. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1162. }
  1163. }
  1164. date = tmpDate.Format(FormatDate)
  1165. case "本月":
  1166. var tmpDate time.Time
  1167. switch appointDay {
  1168. case "第一天":
  1169. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1170. case "最后一天":
  1171. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1172. }
  1173. date = tmpDate.Format(FormatDate)
  1174. case "本季":
  1175. month := currDate.Month()
  1176. var tmpDate time.Time
  1177. switch appointDay {
  1178. case "第一天":
  1179. if month <= 3 {
  1180. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1181. } else if month <= 6 {
  1182. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1183. } else if month <= 9 {
  1184. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1185. } else {
  1186. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1187. }
  1188. case "最后一天":
  1189. if month <= 3 {
  1190. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1191. } else if month <= 6 {
  1192. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1193. } else if month <= 9 {
  1194. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1195. } else {
  1196. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1197. }
  1198. }
  1199. date = tmpDate.Format(FormatDate)
  1200. case "本半年":
  1201. month := currDate.Month()
  1202. var tmpDate time.Time
  1203. switch appointDay {
  1204. case "第一天":
  1205. if month <= 6 {
  1206. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1207. } else {
  1208. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1209. }
  1210. case "最后一天":
  1211. if month <= 6 {
  1212. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1213. } else {
  1214. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1215. }
  1216. }
  1217. date = tmpDate.Format(FormatDate)
  1218. case "本年":
  1219. var tmpDate time.Time
  1220. switch appointDay {
  1221. case "第一天":
  1222. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1223. case "最后一天":
  1224. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1225. }
  1226. date = tmpDate.Format(FormatDate)
  1227. default:
  1228. errMsg = "错误的日期频度:" + frequency
  1229. err = errors.New(errMsg)
  1230. return
  1231. }
  1232. return
  1233. }
  1234. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1235. switch op {
  1236. case "=":
  1237. return a == b
  1238. case ">":
  1239. return a > b
  1240. case ">=":
  1241. return a >= b
  1242. case "<=":
  1243. return a <= b
  1244. case "<":
  1245. return a < b
  1246. }
  1247. return false
  1248. }