common.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "github.com/shopspring/decimal"
  12. "image"
  13. "image/png"
  14. "io"
  15. "math"
  16. "math/rand"
  17. "net"
  18. "net/http"
  19. "os"
  20. "os/exec"
  21. "path"
  22. "regexp"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "unicode"
  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. // Token
  187. func GetToken() string {
  188. randStr := GetRandString(64)
  189. token := MD5(randStr + Md5Key)
  190. tokenLen := 64 - len(token)
  191. return strings.ToUpper(token + GetRandString(tokenLen))
  192. }
  193. // 数据没有记录
  194. func ErrNoRow() string {
  195. //return "<QuerySeter> no row found"
  196. return "record not found"
  197. }
  198. // 判断文件是否存在
  199. func FileIsExist(filePath string) bool {
  200. _, err := os.Stat(filePath)
  201. return err == nil || os.IsExist(err)
  202. }
  203. // 获取图片扩展名
  204. func GetImgExt(file string) (ext string, err error) {
  205. var headerByte []byte
  206. headerByte = make([]byte, 8)
  207. fd, err := os.Open(file)
  208. if err != nil {
  209. return "", err
  210. }
  211. defer fd.Close()
  212. _, err = fd.Read(headerByte)
  213. if err != nil {
  214. return "", err
  215. }
  216. xStr := fmt.Sprintf("%x", headerByte)
  217. switch {
  218. case xStr == "89504e470d0a1a0a":
  219. ext = ".png"
  220. case xStr == "0000010001002020":
  221. ext = ".ico"
  222. case xStr == "0000020001002020":
  223. ext = ".cur"
  224. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  225. ext = ".gif"
  226. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  227. ext = ".tga"
  228. case xStr[:8] == "464f524d":
  229. ext = ".iff"
  230. case xStr[:8] == "52494646":
  231. ext = ".ani"
  232. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  233. ext = ".tiff"
  234. case xStr[:4] == "424d":
  235. ext = ".bmp"
  236. case xStr[:4] == "ffd8":
  237. ext = ".jpg"
  238. case xStr[:2] == "0a":
  239. ext = ".pcx"
  240. default:
  241. ext = ""
  242. }
  243. return ext, nil
  244. }
  245. // 保存图片
  246. func SaveImage(path string, img image.Image) (err error) {
  247. //需要保持的文件
  248. imgfile, err := os.Create(path)
  249. defer imgfile.Close()
  250. // 以PNG格式保存文件
  251. err = png.Encode(imgfile, img)
  252. return err
  253. }
  254. // 下载图片
  255. func DownloadImage(imgUrl string) (filePath string, err error) {
  256. imgPath := "./static/imgs/"
  257. fileName := path.Base(imgUrl)
  258. res, err := http.Get(imgUrl)
  259. if err != nil {
  260. fmt.Println("A error occurred!")
  261. return
  262. }
  263. defer res.Body.Close()
  264. // 获得get请求响应的reader对象
  265. reader := bufio.NewReaderSize(res.Body, 32*1024)
  266. filePath = imgPath + fileName
  267. file, err := os.Create(filePath)
  268. if err != nil {
  269. return
  270. }
  271. // 获得文件的writer对象
  272. writer := bufio.NewWriter(file)
  273. written, _ := io.Copy(writer, reader)
  274. fmt.Printf("Total length: %d \n", written)
  275. return
  276. }
  277. // 保存base64数据为文件
  278. func SaveBase64ToFile(content, path string) error {
  279. data, err := base64.StdEncoding.DecodeString(content)
  280. if err != nil {
  281. return err
  282. }
  283. f, err := os.Create(path)
  284. defer f.Close()
  285. if err != nil {
  286. return err
  287. }
  288. f.Write(data)
  289. return nil
  290. }
  291. func SaveBase64ToFileBySeek(content, path string) (err error) {
  292. data, err := base64.StdEncoding.DecodeString(content)
  293. exist, err := PathExists(path)
  294. if err != nil {
  295. return
  296. }
  297. if !exist {
  298. f, err := os.Create(path)
  299. if err != nil {
  300. return err
  301. }
  302. n, _ := f.Seek(0, 2)
  303. // 从末尾的偏移量开始写入内容
  304. _, err = f.WriteAt([]byte(data), n)
  305. defer f.Close()
  306. } else {
  307. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  308. if err != nil {
  309. return err
  310. }
  311. n, _ := f.Seek(0, 2)
  312. // 从末尾的偏移量开始写入内容
  313. _, err = f.WriteAt([]byte(data), n)
  314. defer f.Close()
  315. }
  316. return nil
  317. }
  318. func PathExists(path string) (bool, error) {
  319. _, err := os.Stat(path)
  320. if err == nil {
  321. return true, nil
  322. }
  323. if os.IsNotExist(err) {
  324. return false, nil
  325. }
  326. return false, err
  327. }
  328. func StartIndex(page, pagesize int) int {
  329. if page > 1 {
  330. return (page - 1) * pagesize
  331. }
  332. return 0
  333. }
  334. func PageCount(count, pagesize int) int {
  335. if count%pagesize > 0 {
  336. return count/pagesize + 1
  337. } else {
  338. return count / pagesize
  339. }
  340. }
  341. func TrimHtml(src string) string {
  342. //将HTML标签全转换成小写
  343. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  344. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  345. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  346. src = re.ReplaceAllString(src, "[图片]")
  347. re, _ = regexp.Compile("class[\\S\\s]+?>")
  348. src = re.ReplaceAllString(src, "")
  349. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  350. src = re.ReplaceAllString(src, "")
  351. return strings.TrimSpace(src)
  352. }
  353. //1556164246 -> 2019-04-25 03:50:46 +0000
  354. //timestamp
  355. func TimeToTimestamp() {
  356. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  357. }
  358. func ToUnicode(text string) string {
  359. textQuoted := strconv.QuoteToASCII(text)
  360. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  361. return textUnquoted
  362. }
  363. func VersionToInt(version string) int {
  364. version = strings.Replace(version, ".", "", -1)
  365. n, _ := strconv.Atoi(version)
  366. return n
  367. }
  368. func IsCheckInList(list []int, s int) bool {
  369. for _, v := range list {
  370. if v == s {
  371. return true
  372. }
  373. }
  374. return false
  375. }
  376. func round(num float64) int {
  377. return int(num + math.Copysign(0.5, num))
  378. }
  379. func toFixed(num float64, precision int) float64 {
  380. output := math.Pow(10, float64(precision))
  381. return float64(round(num*output)) / output
  382. }
  383. // GetWilsonScore returns Wilson Score
  384. func GetWilsonScore(p, n float64) float64 {
  385. if p == 0 && n == 0 {
  386. return 0
  387. }
  388. 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)
  389. }
  390. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  391. func ChangeWordsToNum(str string) (numStr string) {
  392. words := ([]rune)(str)
  393. num := 0
  394. n := 0
  395. for i := 0; i < len(words); i++ {
  396. word := string(words[i : i+1])
  397. switch word {
  398. case "万":
  399. if n == 0 {
  400. n = 1
  401. }
  402. n = n * 10000
  403. num = num*10000 + n
  404. n = 0
  405. case "千":
  406. if n == 0 {
  407. n = 1
  408. }
  409. n = n * 1000
  410. num += n
  411. n = 0
  412. case "百":
  413. if n == 0 {
  414. n = 1
  415. }
  416. n = n * 100
  417. num += n
  418. n = 0
  419. case "十":
  420. if n == 0 {
  421. n = 1
  422. }
  423. n = n * 10
  424. num += n
  425. n = 0
  426. case "一":
  427. n += 1
  428. case "二":
  429. n += 2
  430. case "三":
  431. n += 3
  432. case "四":
  433. n += 4
  434. case "五":
  435. n += 5
  436. case "六":
  437. n += 6
  438. case "七":
  439. n += 7
  440. case "八":
  441. n += 8
  442. case "九":
  443. n += 9
  444. case "零":
  445. default:
  446. if n > 0 {
  447. num += n
  448. n = 0
  449. }
  450. if num == 0 {
  451. numStr += word
  452. } else {
  453. numStr += strconv.Itoa(num) + word
  454. num = 0
  455. }
  456. }
  457. }
  458. if n > 0 {
  459. num += n
  460. n = 0
  461. }
  462. if num != 0 {
  463. numStr += strconv.Itoa(num)
  464. }
  465. return
  466. }
  467. func Sha1(data string) string {
  468. sha1 := sha1.New()
  469. sha1.Write([]byte(data))
  470. return hex.EncodeToString(sha1.Sum([]byte("")))
  471. }
  472. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  473. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  474. out, err := exec.Command("bash", "-c", cmd).Output()
  475. if err != nil {
  476. return
  477. }
  478. outTimes := string(out)
  479. fmt.Println("outTimes:", outTimes)
  480. if outTimes != "" {
  481. timeArr := strings.Split(outTimes, ":")
  482. h := timeArr[0]
  483. m := timeArr[1]
  484. s := timeArr[2]
  485. hInt, err := strconv.Atoi(h)
  486. if err != nil {
  487. return playSeconds, err
  488. }
  489. mInt, err := strconv.Atoi(m)
  490. if err != nil {
  491. return playSeconds, err
  492. }
  493. s = strings.Trim(s, " ")
  494. s = strings.Trim(s, "\n")
  495. sInt, err := strconv.ParseFloat(s, 64)
  496. if err != nil {
  497. return playSeconds, err
  498. }
  499. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  500. }
  501. return
  502. }
  503. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  504. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  505. tradeCode = strings.Trim(tradeCode, " ")
  506. tradeCodeInt, err := strconv.Atoi(tradeCode)
  507. if err != nil {
  508. return
  509. }
  510. tradeCodeInt = tradeCodeInt + 1
  511. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  512. return
  513. }
  514. // excel日期字段格式化 yyyy-mm-dd
  515. func ConvertToFormatDay(excelDaysString string) string {
  516. // 2006-01-02 距离 1900-01-01的天数
  517. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  518. curDiffDay := excelDaysString
  519. b, _ := strconv.Atoi(curDiffDay)
  520. // 获取excel的日期距离2006-01-02的天数
  521. realDiffDay := b - baseDiffDay
  522. //fmt.Println("realDiffDay:",realDiffDay)
  523. // 距离2006-01-02 秒数
  524. realDiffSecond := realDiffDay * 24 * 3600
  525. //fmt.Println("realDiffSecond:",realDiffSecond)
  526. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  527. baseOriginSecond := 1136185445
  528. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  529. return resultTime
  530. }
  531. func CheckPwd(pwd string) bool {
  532. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  533. reg := regexp.MustCompile(compile)
  534. flag := reg.MatchString(pwd)
  535. return flag
  536. }
  537. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  538. // 数字月份必须前置补零
  539. if len(myMonth) == 1 {
  540. myMonth = "0" + myMonth
  541. }
  542. yInt, _ := strconv.Atoi(myYear)
  543. timeLayout := "2006-01-02 15:04:05"
  544. loc, _ := time.LoadLocation("Local")
  545. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  546. newMonth := theTime.Month()
  547. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  548. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  549. return t1, t2
  550. }
  551. // 移除字符串中的空格
  552. func TrimStr(str string) (str2 string) {
  553. if str == "" {
  554. return str
  555. }
  556. return strings.Replace(str, " ", "", -1)
  557. }
  558. // 字符串转换为time
  559. func StrTimeToTime(strTime string) time.Time {
  560. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  561. loc, _ := time.LoadLocation("Local") //重要:获取时区
  562. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  563. return resultTime
  564. }
  565. // 字符串类型时间转周几
  566. func StrDateTimeToWeek(strTime string) string {
  567. var WeekDayMap = map[string]string{
  568. "Monday": "周一",
  569. "Tuesday": "周二",
  570. "Wednesday": "周三",
  571. "Thursday": "周四",
  572. "Friday": "周五",
  573. "Saturday": "周六",
  574. "Sunday": "周日",
  575. }
  576. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  577. startday, _ := time.ParseInLocation("2006-01-02", ctime, time.Local)
  578. staweek_int := startday.Weekday().String()
  579. return WeekDayMap[staweek_int]
  580. }
  581. // 时间格式转年月日字符串
  582. func TimeToStrYmd(time2 time.Time) string {
  583. var Ymd string
  584. year := time2.Year()
  585. month := time2.Format("1")
  586. day1 := time.Now().Day()
  587. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  588. return Ymd
  589. }
  590. // 时间格式去掉时分秒
  591. func TimeRemoveHms(strTime string) string {
  592. var Ymd string
  593. var resultTime = StrTimeToTime(strTime)
  594. year := resultTime.Year()
  595. month := resultTime.Format("01")
  596. day1 := resultTime.Day()
  597. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  598. return Ymd
  599. }
  600. // 时间格式去掉时分秒
  601. func TimeRemoveHms2(strTime string) string {
  602. var Ymd string
  603. var resultTime = StrTimeToTime(strTime)
  604. year := resultTime.Year()
  605. month := resultTime.Format("01")
  606. day1 := resultTime.Day()
  607. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  608. return Ymd
  609. }
  610. // 文章上一次编辑时间
  611. func ArticleLastTime(strTime string) string {
  612. var newTime string
  613. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  614. diffTime := time.Now().Unix() - stamp.Unix()
  615. if diffTime <= 60 {
  616. newTime = "当前"
  617. } else if diffTime < 60*60 {
  618. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  619. } else if diffTime < 24*60*60 {
  620. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  621. } else if diffTime < 30*24*60*60 {
  622. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  623. } else if diffTime < 12*30*24*60*60 {
  624. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  625. } else {
  626. newTime = "1年前"
  627. }
  628. return newTime
  629. }
  630. // 人民币小写转大写
  631. func ConvertNumToCny(num float64) (str string, err error) {
  632. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  633. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  634. // log.Println(sliceUnit[:len(sliceUnit)-2])
  635. s := sliceUnit[len(sliceUnit)-len(strNum):]
  636. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  637. for k, v := range strNum[:] {
  638. str = str + upperDigitUnit[string(v)] + s[k]
  639. }
  640. reg, err := regexp.Compile(`零角零分$`)
  641. str = reg.ReplaceAllString(str, "整")
  642. reg, err = regexp.Compile(`零角`)
  643. str = reg.ReplaceAllString(str, "零")
  644. reg, err = regexp.Compile(`零分$`)
  645. str = reg.ReplaceAllString(str, "整")
  646. reg, err = regexp.Compile(`零[仟佰拾]`)
  647. str = reg.ReplaceAllString(str, "零")
  648. reg, err = regexp.Compile(`零{2,}`)
  649. str = reg.ReplaceAllString(str, "零")
  650. reg, err = regexp.Compile(`零亿`)
  651. str = reg.ReplaceAllString(str, "亿")
  652. reg, err = regexp.Compile(`零万`)
  653. str = reg.ReplaceAllString(str, "万")
  654. reg, err = regexp.Compile(`零*元`)
  655. str = reg.ReplaceAllString(str, "元")
  656. reg, err = regexp.Compile(`亿零{0, 3}万`)
  657. str = reg.ReplaceAllString(str, "^元")
  658. reg, err = regexp.Compile(`零元`)
  659. str = reg.ReplaceAllString(str, "零")
  660. return
  661. }
  662. // GetNowWeekMonday 获取本周周一的时间
  663. func GetNowWeekMonday() time.Time {
  664. offset := int(time.Monday - time.Now().Weekday())
  665. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  666. offset = -6
  667. }
  668. mondayTime := time.Now().AddDate(0, 0, offset)
  669. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  670. return mondayTime
  671. }
  672. // GetNowWeekLastDay 获取本周最后一天的时间
  673. func GetNowWeekLastDay() time.Time {
  674. offset := int(time.Monday - time.Now().Weekday())
  675. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  676. offset = -6
  677. }
  678. firstDayTime := time.Now().AddDate(0, 0, offset)
  679. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  680. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  681. return lastDayTime
  682. }
  683. // GetNowMonthFirstDay 获取本月第一天的时间
  684. func GetNowMonthFirstDay() time.Time {
  685. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  686. return nowMonthFirstDay
  687. }
  688. // GetNowMonthLastDay 获取本月最后一天的时间
  689. func GetNowMonthLastDay() time.Time {
  690. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  691. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  692. return nowMonthLastDay
  693. }
  694. // GetNowQuarterFirstDay 获取本季度第一天的时间
  695. func GetNowQuarterFirstDay() time.Time {
  696. month := int(time.Now().Month())
  697. var nowQuarterFirstDay time.Time
  698. if month >= 1 && month <= 3 {
  699. //1月1号
  700. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  701. } else if month >= 4 && month <= 6 {
  702. //4月1号
  703. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  704. } else if month >= 7 && month <= 9 {
  705. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  706. } else {
  707. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  708. }
  709. return nowQuarterFirstDay
  710. }
  711. // GetNowQuarterLastDay 获取本季度最后一天的时间
  712. func GetNowQuarterLastDay() time.Time {
  713. month := int(time.Now().Month())
  714. var nowQuarterLastDay time.Time
  715. if month >= 1 && month <= 3 {
  716. //03-31 23:59:59
  717. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  718. } else if month >= 4 && month <= 6 {
  719. //06-30 23:59:59
  720. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  721. } else if month >= 7 && month <= 9 {
  722. //09-30 23:59:59
  723. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  724. } else {
  725. //12-31 23:59:59
  726. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  727. }
  728. return nowQuarterLastDay
  729. }
  730. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  731. func GetNowHalfYearFirstDay() time.Time {
  732. month := int(time.Now().Month())
  733. var nowHalfYearLastDay time.Time
  734. if month >= 1 && month <= 6 {
  735. //03-31 23:59:59
  736. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  737. } else {
  738. //12-31 23:59:59
  739. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  740. }
  741. return nowHalfYearLastDay
  742. }
  743. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  744. func GetNowHalfYearLastDay() time.Time {
  745. month := int(time.Now().Month())
  746. var nowHalfYearLastDay time.Time
  747. if month >= 1 && month <= 6 {
  748. //03-31 23:59:59
  749. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  750. } else {
  751. //12-31 23:59:59
  752. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  753. }
  754. return nowHalfYearLastDay
  755. }
  756. // GetNowYearFirstDay 获取当前年的最后一天的时间
  757. func GetNowYearFirstDay() time.Time {
  758. //12-31 23:59:59
  759. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  760. return nowYearFirstDay
  761. }
  762. // GetNowYearLastDay 获取当前年的最后一天的时间
  763. func GetNowYearLastDay() time.Time {
  764. //12-31 23:59:59
  765. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  766. return nowYearLastDay
  767. }
  768. // CalculationDate 计算两个日期之间相差n年m月y天
  769. // FormatPrice 格式化展示金额数字(财务金额展示,小数点前,每三位用,隔开) 1,234,567,898.55
  770. func FormatPrice(price float64) (str string) {
  771. str = decimal.NewFromFloat(price).String()
  772. length := len(str)
  773. if length < 4 {
  774. return str
  775. }
  776. arr := strings.Split(str, ".") //用小数点符号分割字符串,为数组接收
  777. length1 := len(arr[0])
  778. if length1 < 4 {
  779. return str
  780. }
  781. count := (length1 - 1) / 3
  782. for i := 0; i < count; i++ {
  783. arr[0] = arr[0][:length1-(i+1)*3] + "," + arr[0][length1-(i+1)*3:]
  784. }
  785. return strings.Join(arr, ".") //将一系列字符串连接为一个字符串,之间用sep来分隔。
  786. }
  787. // getMonthDay 获取某年某月有多少天
  788. func getMonthDay(year, month int) (days int) {
  789. if month != 2 {
  790. if month == 4 || month == 6 || month == 9 || month == 11 {
  791. days = 30
  792. } else {
  793. days = 31
  794. }
  795. } else {
  796. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  797. days = 29
  798. } else {
  799. days = 28
  800. }
  801. }
  802. return
  803. }
  804. func SaveToFile(content, path string) error {
  805. f, err := os.Create(path)
  806. defer f.Close()
  807. if err != nil {
  808. return err
  809. }
  810. f.Write([]byte(content))
  811. return nil
  812. }
  813. // HideString 给字段加***(从字符串中间替换,少于需要替换的长度,那么就补全*的长度)
  814. // src 待*字符串
  815. // hideLen 需要加*的长度
  816. func HideString(src string, hideLen int) string {
  817. if src == "" {
  818. return src
  819. }
  820. str := []rune(src)
  821. if hideLen == 0 {
  822. hideLen = 4
  823. }
  824. hideStr := ""
  825. for i := 0; i < hideLen; i++ {
  826. hideStr += "*"
  827. }
  828. strLen := len(str)
  829. // 字符长度是1
  830. if strLen == 1 {
  831. return string(str[:1]) + hideStr
  832. }
  833. //字符长度大于1,但是小于等于需要隐藏的字符长度,那么就隐藏中间,保留前后各一位字符
  834. if strLen <= hideLen+2 {
  835. return string(str[:1]) + hideStr + string(str[strLen-1:])
  836. }
  837. subLen := strLen - hideLen //剩余需要展示的字符长度
  838. decimal.NewFromFloat(2)
  839. frontLenDecimal := decimal.NewFromInt(int64(subLen)).Div(decimal.NewFromInt(2)) //前面需要展示的字符的长度
  840. frontLen := frontLenDecimal.Floor().IntPart()
  841. return string(str[:frontLen]) + hideStr + string(str[frontLen+int64(hideLen):])
  842. }
  843. // 用户参会时间转换
  844. func GetAttendanceDetailSeconds(secondNum int) string {
  845. var timeStr string
  846. if secondNum <= 60 {
  847. if secondNum < 10 {
  848. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  849. } else {
  850. timeStr = strconv.Itoa(secondNum) + "''"
  851. }
  852. } else {
  853. var remainderStr string
  854. remainderNum := secondNum % 60
  855. minuteNum := secondNum / 60
  856. if remainderNum < 10 {
  857. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  858. } else {
  859. remainderStr = strconv.Itoa(remainderNum) + "''"
  860. }
  861. if minuteNum < 10 {
  862. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  863. } else {
  864. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  865. }
  866. }
  867. return timeStr
  868. }
  869. // SubStr 截取字符串(中文)
  870. func SubStr(str string, subLen int) string {
  871. strRune := []rune(str)
  872. bodyRuneLen := len(strRune)
  873. if bodyRuneLen > subLen {
  874. bodyRuneLen = subLen
  875. }
  876. str = string(strRune[:bodyRuneLen])
  877. return str
  878. }
  879. func GetLocalIP() (ip string, err error) {
  880. addrs, err := net.InterfaceAddrs()
  881. if err != nil {
  882. return
  883. }
  884. for _, addr := range addrs {
  885. ipAddr, ok := addr.(*net.IPNet)
  886. if !ok {
  887. continue
  888. }
  889. if ipAddr.IP.IsLoopback() {
  890. continue
  891. }
  892. if !ipAddr.IP.IsGlobalUnicast() {
  893. continue
  894. }
  895. return ipAddr.IP.String(), nil
  896. }
  897. return
  898. }
  899. func PrintLog(params ...string) {
  900. _, file, line, ok := runtime.Caller(1)
  901. fmt.Println(file, line, ok, params)
  902. }
  903. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  904. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  905. for _, id := range idStrList {
  906. if id == searchId {
  907. has = true
  908. return
  909. }
  910. }
  911. return
  912. }
  913. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该Int值)
  914. func InArrayByInt(idStrList []int, searchId int) (has bool) {
  915. for _, id := range idStrList {
  916. if id == searchId {
  917. has = true
  918. return
  919. }
  920. }
  921. return
  922. }
  923. // GetOrmInReplace 获取orm的in查询替换?的方法
  924. func GetOrmInReplace(num int) string {
  925. template := make([]string, num)
  926. for i := 0; i < num; i++ {
  927. template[i] = "?"
  928. }
  929. return strings.Join(template, ",")
  930. }
  931. // GetTimeSubDay 计算两个时间的自然日期差
  932. func GetTimeSubDay(t1, t2 time.Time) int {
  933. var day int
  934. swap := false
  935. if t1.Unix() > t2.Unix() {
  936. t1, t2 = t2, t1
  937. swap = true
  938. }
  939. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  940. day = int(t2.Sub(t1).Hours() / 24)
  941. // 计算在t1+两个时间的余数之后天数是否有变化
  942. if t1_.Day() != t1.Day() {
  943. day += 1
  944. }
  945. if swap {
  946. day = -day
  947. }
  948. return day
  949. }
  950. // GetFrequencyEndDay 根据当前时间和频度,获取该频度下最后一天的日期
  951. func GetFrequencyEndDay(currDate time.Time, frequency string) (endDate time.Time) {
  952. switch frequency {
  953. case "周度":
  954. // 如果当前就是最后一天,那么就直接返回本日期就好了
  955. if currDate.Weekday() == 0 {
  956. endDate = currDate
  957. } else {
  958. endDate = currDate.AddDate(0, 0, 7-int(currDate.Weekday()))
  959. }
  960. case "旬度":
  961. nextDay := currDate.AddDate(0, 0, 1)
  962. if nextDay.Day() == 1 || currDate.Day() == 10 || currDate.Day() == 20 {
  963. //如果是每月10、20、最后一天,那么就直接返回本日期就好了
  964. endDate = currDate
  965. } else {
  966. if currDate.Day() < 10 { // 每月10号
  967. endDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, time.Local)
  968. } else if currDate.Day() < 20 { // 每月10号
  969. endDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, time.Local)
  970. } else {
  971. // 下旬,多种可能,最大天数可能存在8天,9天,10天,11天,
  972. tmpNextMonth := currDate.AddDate(0, 0, 13)
  973. endDate = time.Date(tmpNextMonth.Year(), tmpNextMonth.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  974. }
  975. }
  976. case "月度":
  977. nextDay := currDate.AddDate(0, 0, 1)
  978. if nextDay.Day() == 1 {
  979. //如果是每月的最后一天,那么就直接返回本日期就好了
  980. endDate = currDate
  981. } else {
  982. endDate = time.Date(nextDay.Year(), nextDay.Month()+1, 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  983. }
  984. case "季度":
  985. nextDay := currDate.AddDate(0, 0, 1)
  986. if (nextDay.Month() == 1 || nextDay.Month() == 4 || nextDay.Month() == 7 || nextDay.Month() == 10) && nextDay.Day() == 1 {
  987. //如果是每季的最后一天,那么就直接返回本日期就好了
  988. endDate = currDate
  989. } else {
  990. if currDate.Month() < 4 { // 1季度
  991. endDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, time.Local)
  992. } else if currDate.Month() < 7 { // 2季度
  993. endDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, time.Local)
  994. } else if currDate.Month() < 10 { // 3季度
  995. endDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, time.Local)
  996. } else {
  997. // 4季度
  998. endDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  999. }
  1000. }
  1001. case "年度":
  1002. endDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  1003. default:
  1004. endDate = currDate
  1005. return
  1006. }
  1007. return
  1008. }
  1009. // CheckFrequency 获取两个频度之间是否相对低高频
  1010. // 大于0,代表左侧是高频(例:左侧:日度,右侧:周度)
  1011. // 等于0,代表同频
  1012. // 小于0,代表右侧是高频(例:左侧:周度,右侧:日度)
  1013. func CheckFrequency(leftFrequency, rightFrequency string) int {
  1014. frequencyMap := map[string]int{
  1015. "年度": 0,
  1016. "半年度": 1,
  1017. "季度": 2,
  1018. "月度": 3,
  1019. "旬度": 4,
  1020. "周度": 5,
  1021. "日度": 6,
  1022. }
  1023. return frequencyMap[leftFrequency] - frequencyMap[rightFrequency]
  1024. }
  1025. // 将下划线命名转为驼峰命名
  1026. func SnakeToCamel(s string) string {
  1027. var result string
  1028. upper := true
  1029. for _, c := range s {
  1030. if c == '_' {
  1031. upper = true
  1032. continue
  1033. }
  1034. if upper {
  1035. result += string(unicode.ToUpper(c))
  1036. upper = false
  1037. } else {
  1038. result += string(c)
  1039. }
  1040. }
  1041. return result
  1042. }
  1043. // 将驼峰命名转为下划线命名
  1044. func CamelToSnake(s string) string {
  1045. var result string
  1046. for i, c := range s {
  1047. if unicode.IsUpper(c) {
  1048. if i > 0 {
  1049. result += "_"
  1050. }
  1051. result += string(unicode.ToLower(c))
  1052. } else {
  1053. result += string(c)
  1054. }
  1055. }
  1056. return result
  1057. }
  1058. func TimeTransferString(format string, t time.Time) string {
  1059. str := t.Format(format)
  1060. if t.IsZero() {
  1061. return ""
  1062. }
  1063. return str
  1064. }
  1065. // GetEdbRefreshStartDate
  1066. // @Description: 获取开始刷新时间
  1067. // @author: Roc
  1068. // @datetime 2024-02-05 11:23:55
  1069. // @param startDate string
  1070. // @return string
  1071. func GetEdbRefreshStartDate(startDate string) string {
  1072. // 没有传入日期,或者日期异常的话,那么就是从1990-01-01开始
  1073. if startDate == `` || strings.Contains(startDate, "0000-") {
  1074. return "1990-01-01"
  1075. }
  1076. return startDate
  1077. }
  1078. // GetEdbRefreshEndDate
  1079. // @Description: 获取结束刷新时间
  1080. // @author: Roc
  1081. // @datetime 2024-02-05 11:23:55
  1082. // @param startDate string
  1083. // @return string
  1084. func GetEdbRefreshEndDate(endDate string) string {
  1085. // 没有传入日期,或者日期异常的话,那么就是从1990-01-01开始
  1086. if endDate == `` || strings.Contains(endDate, "0000-") {
  1087. return time.Now().Format(FormatDate)
  1088. }
  1089. return endDate
  1090. }
  1091. func DealExcelDate(date string) (newDate time.Time, err error) {
  1092. /*newDate, err = dateparse.ParseAny(date)
  1093. if err != nil {
  1094. return
  1095. }
  1096. newDate = time.Date(newDate.Year(), newDate.Month(), newDate.Day(), 0, 0, 0, 0, time.Local)*/
  1097. if strings.Contains(date, "/") {
  1098. newDate, err = time.ParseInLocation("2006/01/02", date, time.Local)
  1099. return
  1100. } else {
  1101. newDate, err = time.ParseInLocation(FormatDate, date, time.Local)
  1102. return
  1103. }
  1104. return
  1105. }
  1106. // FloatAlmostEqual 判断两个浮点数是否相等
  1107. func FloatAlmostEqual(a, b float64) bool {
  1108. epsilon := 1e-9 // 容差值
  1109. return math.Abs(a-b) <= epsilon
  1110. }
  1111. // VerifyFrequency
  1112. // @Description: 校验频度是否合规
  1113. // @author: Roc
  1114. // @datetime 2024-04-26 13:30:22
  1115. // @param frequency string 待校验的频度
  1116. // @return bool
  1117. func VerifyFrequency(frequency string) bool {
  1118. return InArrayByStr([]string{"年度", "半年度", "季度", "月度", "旬度", "周度", "日度"}, frequency)
  1119. }
  1120. // DateConvMysqlConvMongo
  1121. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1122. // @author: Roc
  1123. // @datetime 2024-05-08 11:03:26
  1124. // @param dateCon string
  1125. func DateConvMysqlConvMongo(dateCon string) string {
  1126. cond := ""
  1127. switch dateCon {
  1128. case "=":
  1129. cond = "$eq"
  1130. case "<":
  1131. cond = "$lt"
  1132. case "<=":
  1133. cond = "$lte"
  1134. case ">":
  1135. cond = "$gt"
  1136. case ">=":
  1137. cond = "$gte"
  1138. }
  1139. return cond
  1140. }
  1141. // GenerateEdbCodeMap 当前已经生成的指标编码map(暂时不做定时数据清理了,因为数据不大,我们至少每个月会重启一次,所以暂时不做定时数据清理)
  1142. var GenerateEdbCodeMap = map[string]bool{}
  1143. // GenerateEdbCode
  1144. // @Description: 生成指标编码
  1145. // @author: Roc
  1146. // @datetime 2024-06-05 09:49:53
  1147. // @param num int
  1148. // @param pre string 前缀
  1149. // @return edbCode string
  1150. // @return err error
  1151. func GenerateEdbCode(num int, pre string) (edbCode string, err error) {
  1152. if num >= 10 {
  1153. err = errors.New("指标编码生成失败,请重新生成")
  1154. return
  1155. }
  1156. // 4位随机数
  1157. randStr := GetRandDigit(4)
  1158. // 年月日时分秒+4位随机数
  1159. edbCode = `C` + pre + time.Now().Format(FormatShortDateTimeUnSpace) + randStr
  1160. if _, ok := GenerateEdbCodeMap[edbCode]; ok {
  1161. num++
  1162. edbCode, err = GenerateEdbCode(num, pre)
  1163. }
  1164. GenerateEdbCodeMap[edbCode] = true
  1165. return
  1166. }
  1167. // InsertStr2StrIdx 可分隔的字符串中插入指定字符串, 例如: CO1 Comdty插入V => CO1 V Comdty
  1168. func InsertStr2StrIdx(str, sep string, idx int, value string) string {
  1169. str = strings.TrimSpace(str)
  1170. // 默认以空格作为分隔符
  1171. if sep == "" {
  1172. sep = " "
  1173. }
  1174. slice := strings.Split(str, sep)
  1175. if len(slice) < 2 {
  1176. return str
  1177. }
  1178. // 如果idx不在切片的有效范围内,直接返回原字符串
  1179. if idx < 0 || idx > len(slice) {
  1180. return str
  1181. }
  1182. slice = append(slice[:idx], append([]string{value}, slice[idx:]...)...)
  1183. return strings.Join(slice, sep)
  1184. }
  1185. // FormatFloatPlaces 格式化浮点数位数
  1186. func FormatFloatPlaces(val float64, places int32) (newVal float64, err error) {
  1187. if places <= 0 {
  1188. places = 4
  1189. }
  1190. strNewVal := decimal.NewFromFloat(val).Round(places).String()
  1191. di, e := decimal.NewFromString(strNewVal)
  1192. if e != nil {
  1193. err = fmt.Errorf("NewFromString err: %v", e)
  1194. return
  1195. }
  1196. newVal, _ = di.Float64()
  1197. return
  1198. }
  1199. // handleSystemAppointDateT
  1200. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1201. // @author: Roc
  1202. // @datetime2023-10-27 09:31:35
  1203. // @param Frequency string
  1204. // @param Day string
  1205. // @return date string
  1206. // @return err error
  1207. // @return errMsg string
  1208. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1209. //currDate := time.Now()
  1210. switch frequency {
  1211. case "本周":
  1212. day := int(currDate.Weekday())
  1213. if day == 0 { // 周日
  1214. day = 7
  1215. }
  1216. num := 0
  1217. switch appointDay {
  1218. case "周一":
  1219. num = 1
  1220. case "周二":
  1221. num = 2
  1222. case "周三":
  1223. num = 3
  1224. case "周四":
  1225. num = 4
  1226. case "周五":
  1227. num = 5
  1228. case "周六":
  1229. num = 6
  1230. case "周日":
  1231. num = 7
  1232. }
  1233. day = num - day
  1234. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1235. case "本旬":
  1236. day := currDate.Day()
  1237. var tmpDate time.Time
  1238. switch appointDay {
  1239. case "第一天":
  1240. if day <= 10 {
  1241. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1242. } else if day <= 20 {
  1243. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1244. } else {
  1245. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1246. }
  1247. case "最后一天":
  1248. if day <= 10 {
  1249. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1250. } else if day <= 20 {
  1251. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1252. } else {
  1253. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  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(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1262. case "最后一天":
  1263. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1264. }
  1265. date = tmpDate.Format(FormatDate)
  1266. case "本季":
  1267. month := currDate.Month()
  1268. var tmpDate time.Time
  1269. switch appointDay {
  1270. case "第一天":
  1271. if month <= 3 {
  1272. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1273. } else if month <= 6 {
  1274. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1275. } else if month <= 9 {
  1276. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1277. } else {
  1278. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1279. }
  1280. case "最后一天":
  1281. if month <= 3 {
  1282. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1283. } else if month <= 6 {
  1284. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1285. } else if month <= 9 {
  1286. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1287. } else {
  1288. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1289. }
  1290. }
  1291. date = tmpDate.Format(FormatDate)
  1292. case "本半年":
  1293. month := currDate.Month()
  1294. var tmpDate time.Time
  1295. switch appointDay {
  1296. case "第一天":
  1297. if month <= 6 {
  1298. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1299. } else {
  1300. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1301. }
  1302. case "最后一天":
  1303. if month <= 6 {
  1304. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1305. } else {
  1306. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1307. }
  1308. }
  1309. date = tmpDate.Format(FormatDate)
  1310. case "本年":
  1311. var tmpDate time.Time
  1312. switch appointDay {
  1313. case "第一天":
  1314. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1315. case "最后一天":
  1316. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1317. }
  1318. date = tmpDate.Format(FormatDate)
  1319. default:
  1320. errMsg = "错误的日期频度:" + frequency
  1321. err = errors.New(errMsg)
  1322. return
  1323. }
  1324. return
  1325. }
  1326. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1327. switch op {
  1328. case "=":
  1329. return a == b
  1330. case ">":
  1331. return a > b
  1332. case ">=":
  1333. return a >= b
  1334. case "<=":
  1335. return a <= b
  1336. case "<":
  1337. return a < b
  1338. }
  1339. return false
  1340. }
  1341. // IsDivideZero
  1342. // @Description: 判断是否分母为0的bug
  1343. // @author: Roc
  1344. // @datetime 2024-08-23 11:21:25
  1345. // @param err error
  1346. // @return bool
  1347. func IsDivideZero(err error) bool {
  1348. if err == nil {
  1349. return false
  1350. }
  1351. //if strings.Contains(err.Error(), "divide by zero") {
  1352. // return true
  1353. //}
  1354. if strings.Contains(err.Error(), "division by zero") {
  1355. return true
  1356. }
  1357. return false
  1358. }
  1359. // GetTradingDays 获取开始时间至结束时间之间的交易日期(日度)
  1360. func GetTradingDays(startDate, endDate time.Time) []time.Time {
  1361. var tradingDays []time.Time
  1362. for curr := startDate; !curr.After(endDate); curr = curr.AddDate(0, 0, 1) {
  1363. if curr.Weekday() >= time.Monday && curr.Weekday() <= time.Friday {
  1364. tradingDays = append(tradingDays, curr)
  1365. }
  1366. }
  1367. return tradingDays
  1368. }