common.go 32 KB

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