common.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  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. return "?"
  931. }
  932. // GetTimeSubDay 计算两个时间的自然日期差
  933. func GetTimeSubDay(t1, t2 time.Time) int {
  934. var day int
  935. swap := false
  936. if t1.Unix() > t2.Unix() {
  937. t1, t2 = t2, t1
  938. swap = true
  939. }
  940. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  941. day = int(t2.Sub(t1).Hours() / 24)
  942. // 计算在t1+两个时间的余数之后天数是否有变化
  943. if t1_.Day() != t1.Day() {
  944. day += 1
  945. }
  946. if swap {
  947. day = -day
  948. }
  949. return day
  950. }
  951. // GetFrequencyEndDay 根据当前时间和频度,获取该频度下最后一天的日期
  952. func GetFrequencyEndDay(currDate time.Time, frequency string) (endDate time.Time) {
  953. switch frequency {
  954. case "周度":
  955. // 如果当前就是最后一天,那么就直接返回本日期就好了
  956. if currDate.Weekday() == 0 {
  957. endDate = currDate
  958. } else {
  959. endDate = currDate.AddDate(0, 0, 7-int(currDate.Weekday()))
  960. }
  961. case "旬度":
  962. nextDay := currDate.AddDate(0, 0, 1)
  963. if nextDay.Day() == 1 || currDate.Day() == 10 || currDate.Day() == 20 {
  964. //如果是每月10、20、最后一天,那么就直接返回本日期就好了
  965. endDate = currDate
  966. } else {
  967. if currDate.Day() < 10 { // 每月10号
  968. endDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, time.Local)
  969. } else if currDate.Day() < 20 { // 每月10号
  970. endDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, time.Local)
  971. } else {
  972. // 下旬,多种可能,最大天数可能存在8天,9天,10天,11天,
  973. tmpNextMonth := currDate.AddDate(0, 0, 13)
  974. endDate = time.Date(tmpNextMonth.Year(), tmpNextMonth.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  975. }
  976. }
  977. case "月度":
  978. nextDay := currDate.AddDate(0, 0, 1)
  979. if nextDay.Day() == 1 {
  980. //如果是每月的最后一天,那么就直接返回本日期就好了
  981. endDate = currDate
  982. } else {
  983. endDate = time.Date(nextDay.Year(), nextDay.Month()+1, 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  984. }
  985. case "季度":
  986. nextDay := currDate.AddDate(0, 0, 1)
  987. if (nextDay.Month() == 1 || nextDay.Month() == 4 || nextDay.Month() == 7 || nextDay.Month() == 10) && nextDay.Day() == 1 {
  988. //如果是每季的最后一天,那么就直接返回本日期就好了
  989. endDate = currDate
  990. } else {
  991. if currDate.Month() < 4 { // 1季度
  992. endDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, time.Local)
  993. } else if currDate.Month() < 7 { // 2季度
  994. endDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, time.Local)
  995. } else if currDate.Month() < 10 { // 3季度
  996. endDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, time.Local)
  997. } else {
  998. // 4季度
  999. endDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  1000. }
  1001. }
  1002. case "年度":
  1003. endDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  1004. default:
  1005. endDate = currDate
  1006. return
  1007. }
  1008. return
  1009. }
  1010. // CheckFrequency 获取两个频度之间是否相对低高频
  1011. // 大于0,代表左侧是高频(例:左侧:日度,右侧:周度)
  1012. // 等于0,代表同频
  1013. // 小于0,代表右侧是高频(例:左侧:周度,右侧:日度)
  1014. func CheckFrequency(leftFrequency, rightFrequency string) int {
  1015. frequencyMap := map[string]int{
  1016. "年度": 0,
  1017. "半年度": 1,
  1018. "季度": 2,
  1019. "月度": 3,
  1020. "旬度": 4,
  1021. "周度": 5,
  1022. "日度": 6,
  1023. }
  1024. return frequencyMap[leftFrequency] - frequencyMap[rightFrequency]
  1025. }
  1026. // 将下划线命名转为驼峰命名
  1027. func SnakeToCamel(s string) string {
  1028. var result string
  1029. upper := true
  1030. for _, c := range s {
  1031. if c == '_' {
  1032. upper = true
  1033. continue
  1034. }
  1035. if upper {
  1036. result += string(unicode.ToUpper(c))
  1037. upper = false
  1038. } else {
  1039. result += string(c)
  1040. }
  1041. }
  1042. return result
  1043. }
  1044. // 将驼峰命名转为下划线命名
  1045. func CamelToSnake(s string) string {
  1046. var result string
  1047. for i, c := range s {
  1048. if unicode.IsUpper(c) {
  1049. if i > 0 {
  1050. result += "_"
  1051. }
  1052. result += string(unicode.ToLower(c))
  1053. } else {
  1054. result += string(c)
  1055. }
  1056. }
  1057. return result
  1058. }
  1059. func TimeTransferString(format string, t time.Time) string {
  1060. str := t.Format(format)
  1061. if t.IsZero() {
  1062. return ""
  1063. }
  1064. return str
  1065. }
  1066. // GetEdbRefreshStartDate
  1067. // @Description: 获取开始刷新时间
  1068. // @author: Roc
  1069. // @datetime 2024-02-05 11:23:55
  1070. // @param startDate string
  1071. // @return string
  1072. func GetEdbRefreshStartDate(startDate string) string {
  1073. // 没有传入日期,或者日期异常的话,那么就是从1990-01-01开始
  1074. if startDate == `` || strings.Contains(startDate, "0000-") {
  1075. return "1990-01-01"
  1076. }
  1077. return startDate
  1078. }
  1079. // GetEdbRefreshEndDate
  1080. // @Description: 获取结束刷新时间
  1081. // @author: Roc
  1082. // @datetime 2024-02-05 11:23:55
  1083. // @param startDate string
  1084. // @return string
  1085. func GetEdbRefreshEndDate(endDate string) string {
  1086. // 没有传入日期,或者日期异常的话,那么就是从1990-01-01开始
  1087. if endDate == `` || strings.Contains(endDate, "0000-") {
  1088. return time.Now().Format(FormatDate)
  1089. }
  1090. return endDate
  1091. }
  1092. func DealExcelDate(date string) (newDate time.Time, err error) {
  1093. /*newDate, err = dateparse.ParseAny(date)
  1094. if err != nil {
  1095. return
  1096. }
  1097. newDate = time.Date(newDate.Year(), newDate.Month(), newDate.Day(), 0, 0, 0, 0, time.Local)*/
  1098. if strings.Contains(date, "/") {
  1099. newDate, err = time.ParseInLocation("2006/01/02", date, time.Local)
  1100. return
  1101. } else {
  1102. newDate, err = time.ParseInLocation(FormatDate, date, time.Local)
  1103. return
  1104. }
  1105. return
  1106. }
  1107. // FloatAlmostEqual 判断两个浮点数是否相等
  1108. func FloatAlmostEqual(a, b float64) bool {
  1109. epsilon := 1e-9 // 容差值
  1110. return math.Abs(a-b) <= epsilon
  1111. }
  1112. // VerifyFrequency
  1113. // @Description: 校验频度是否合规
  1114. // @author: Roc
  1115. // @datetime 2024-04-26 13:30:22
  1116. // @param frequency string 待校验的频度
  1117. // @return bool
  1118. func VerifyFrequency(frequency string) bool {
  1119. return InArrayByStr([]string{"年度", "半年度", "季度", "月度", "旬度", "周度", "日度"}, frequency)
  1120. }
  1121. // DateConvMysqlConvMongo
  1122. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1123. // @author: Roc
  1124. // @datetime 2024-05-08 11:03:26
  1125. // @param dateCon string
  1126. func DateConvMysqlConvMongo(dateCon string) string {
  1127. cond := ""
  1128. switch dateCon {
  1129. case "=":
  1130. cond = "$eq"
  1131. case "<":
  1132. cond = "$lt"
  1133. case "<=":
  1134. cond = "$lte"
  1135. case ">":
  1136. cond = "$gt"
  1137. case ">=":
  1138. cond = "$gte"
  1139. }
  1140. return cond
  1141. }
  1142. // GenerateEdbCodeMap 当前已经生成的指标编码map(暂时不做定时数据清理了,因为数据不大,我们至少每个月会重启一次,所以暂时不做定时数据清理)
  1143. var GenerateEdbCodeMap = map[string]bool{}
  1144. // GenerateEdbCode
  1145. // @Description: 生成指标编码
  1146. // @author: Roc
  1147. // @datetime 2024-06-05 09:49:53
  1148. // @param num int
  1149. // @param pre string 前缀
  1150. // @return edbCode string
  1151. // @return err error
  1152. func GenerateEdbCode(num int, pre string) (edbCode string, err error) {
  1153. if num >= 10 {
  1154. err = errors.New("指标编码生成失败,请重新生成")
  1155. return
  1156. }
  1157. // 4位随机数
  1158. randStr := GetRandDigit(4)
  1159. // 年月日时分秒+4位随机数
  1160. edbCode = `C` + pre + time.Now().Format(FormatShortDateTimeUnSpace) + randStr
  1161. if _, ok := GenerateEdbCodeMap[edbCode]; ok {
  1162. num++
  1163. edbCode, err = GenerateEdbCode(num, pre)
  1164. }
  1165. GenerateEdbCodeMap[edbCode] = true
  1166. return
  1167. }
  1168. // InsertStr2StrIdx 可分隔的字符串中插入指定字符串, 例如: CO1 Comdty插入V => CO1 V Comdty
  1169. func InsertStr2StrIdx(str, sep string, idx int, value string) string {
  1170. str = strings.TrimSpace(str)
  1171. // 默认以空格作为分隔符
  1172. if sep == "" {
  1173. sep = " "
  1174. }
  1175. slice := strings.Split(str, sep)
  1176. if len(slice) < 2 {
  1177. return str
  1178. }
  1179. // 如果idx不在切片的有效范围内,直接返回原字符串
  1180. if idx < 0 || idx > len(slice) {
  1181. return str
  1182. }
  1183. slice = append(slice[:idx], append([]string{value}, slice[idx:]...)...)
  1184. return strings.Join(slice, sep)
  1185. }
  1186. // FormatFloatPlaces 格式化浮点数位数
  1187. func FormatFloatPlaces(val float64, places int32) (newVal float64, err error) {
  1188. if places <= 0 {
  1189. places = 4
  1190. }
  1191. strNewVal := decimal.NewFromFloat(val).Round(places).String()
  1192. di, e := decimal.NewFromString(strNewVal)
  1193. if e != nil {
  1194. err = fmt.Errorf("NewFromString err: %v", e)
  1195. return
  1196. }
  1197. newVal, _ = di.Float64()
  1198. return
  1199. }
  1200. // handleSystemAppointDateT
  1201. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1202. // @author: Roc
  1203. // @datetime2023-10-27 09:31:35
  1204. // @param Frequency string
  1205. // @param Day string
  1206. // @return date string
  1207. // @return err error
  1208. // @return errMsg string
  1209. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1210. //currDate := time.Now()
  1211. switch frequency {
  1212. case "本周":
  1213. day := int(currDate.Weekday())
  1214. if day == 0 { // 周日
  1215. day = 7
  1216. }
  1217. num := 0
  1218. switch appointDay {
  1219. case "周一":
  1220. num = 1
  1221. case "周二":
  1222. num = 2
  1223. case "周三":
  1224. num = 3
  1225. case "周四":
  1226. num = 4
  1227. case "周五":
  1228. num = 5
  1229. case "周六":
  1230. num = 6
  1231. case "周日":
  1232. num = 7
  1233. }
  1234. day = num - day
  1235. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1236. case "本旬":
  1237. day := currDate.Day()
  1238. var tmpDate time.Time
  1239. switch appointDay {
  1240. case "第一天":
  1241. if day <= 10 {
  1242. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1243. } else if day <= 20 {
  1244. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1245. } else {
  1246. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1247. }
  1248. case "最后一天":
  1249. if day <= 10 {
  1250. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1251. } else if day <= 20 {
  1252. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1253. } else {
  1254. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1255. }
  1256. }
  1257. date = tmpDate.Format(FormatDate)
  1258. case "本月":
  1259. var tmpDate time.Time
  1260. switch appointDay {
  1261. case "第一天":
  1262. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1263. case "最后一天":
  1264. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1265. }
  1266. date = tmpDate.Format(FormatDate)
  1267. case "本季":
  1268. month := currDate.Month()
  1269. var tmpDate time.Time
  1270. switch appointDay {
  1271. case "第一天":
  1272. if month <= 3 {
  1273. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1274. } else if month <= 6 {
  1275. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1276. } else if month <= 9 {
  1277. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1278. } else {
  1279. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1280. }
  1281. case "最后一天":
  1282. if month <= 3 {
  1283. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1284. } else if month <= 6 {
  1285. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1286. } else if month <= 9 {
  1287. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1288. } else {
  1289. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1290. }
  1291. }
  1292. date = tmpDate.Format(FormatDate)
  1293. case "本半年":
  1294. month := currDate.Month()
  1295. var tmpDate time.Time
  1296. switch appointDay {
  1297. case "第一天":
  1298. if month <= 6 {
  1299. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1300. } else {
  1301. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1302. }
  1303. case "最后一天":
  1304. if month <= 6 {
  1305. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1306. } else {
  1307. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1308. }
  1309. }
  1310. date = tmpDate.Format(FormatDate)
  1311. case "本年":
  1312. var tmpDate time.Time
  1313. switch appointDay {
  1314. case "第一天":
  1315. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1316. case "最后一天":
  1317. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1318. }
  1319. date = tmpDate.Format(FormatDate)
  1320. default:
  1321. errMsg = "错误的日期频度:" + frequency
  1322. err = errors.New(errMsg)
  1323. return
  1324. }
  1325. return
  1326. }
  1327. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1328. switch op {
  1329. case "=":
  1330. return a == b
  1331. case ">":
  1332. return a > b
  1333. case ">=":
  1334. return a >= b
  1335. case "<=":
  1336. return a <= b
  1337. case "<":
  1338. return a < b
  1339. }
  1340. return false
  1341. }
  1342. // IsDivideZero
  1343. // @Description: 判断是否分母为0的bug
  1344. // @author: Roc
  1345. // @datetime 2024-08-23 11:21:25
  1346. // @param err error
  1347. // @return bool
  1348. func IsDivideZero(err error) bool {
  1349. if err == nil {
  1350. return false
  1351. }
  1352. //if strings.Contains(err.Error(), "divide by zero") {
  1353. // return true
  1354. //}
  1355. if strings.Contains(err.Error(), "division by zero") {
  1356. return true
  1357. }
  1358. return false
  1359. }
  1360. // GetTradingDays 获取开始时间至结束时间之间的交易日期(日度)
  1361. func GetTradingDays(startDate, endDate time.Time) []time.Time {
  1362. var tradingDays []time.Time
  1363. for curr := startDate; !curr.After(endDate); curr = curr.AddDate(0, 0, 1) {
  1364. if curr.Weekday() >= time.Monday && curr.Weekday() <= time.Friday {
  1365. tradingDays = append(tradingDays, curr)
  1366. }
  1367. }
  1368. return tradingDays
  1369. }