common.go 32 KB

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