common.go 26 KB

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