common.go 26 KB

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