common.go 39 KB

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