common.go 29 KB

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