common.go 34 KB

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