common.go 31 KB

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