common.go 34 KB

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