common.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. package utils
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "image"
  12. "image/png"
  13. "math"
  14. "math/rand"
  15. "os"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. //随机数种子
  22. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  23. func GetRandString(size int) string {
  24. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  25. randomSb := ""
  26. digitSize := len(allLetterDigit)
  27. for i := 0; i < size; i++ {
  28. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  29. }
  30. return randomSb
  31. }
  32. func GetRandStringNoSpecialChar(size int) string {
  33. 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"}
  34. randomSb := ""
  35. digitSize := len(allLetterDigit)
  36. for i := 0; i < size; i++ {
  37. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  38. }
  39. return randomSb
  40. }
  41. func StringsToJSON(str string) string {
  42. rs := []rune(str)
  43. jsons := ""
  44. for _, r := range rs {
  45. rint := int(r)
  46. if rint < 128 {
  47. jsons += string(r)
  48. } else {
  49. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  50. }
  51. }
  52. return jsons
  53. }
  54. //序列化
  55. func ToString(v interface{}) string {
  56. data, _ := json.Marshal(v)
  57. return string(data)
  58. }
  59. //md5加密
  60. func MD5(data string) string {
  61. m := md5.Sum([]byte(data))
  62. return hex.EncodeToString(m[:])
  63. }
  64. // HmacMd5 HmacMd5加密
  65. func HmacMd5(key, data string) string {
  66. h := hmac.New(md5.New, []byte(key))
  67. h.Write([]byte(data))
  68. return hex.EncodeToString(h.Sum([]byte("")))
  69. }
  70. // 获取数字随机字符
  71. func GetRandDigit(n int) string {
  72. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  73. }
  74. // 获取随机数
  75. func GetRandNumber(n int) int {
  76. return rnd.Intn(n)
  77. }
  78. func GetRandInt(min, max int) int {
  79. if min >= max || min == 0 || max == 0 {
  80. return max
  81. }
  82. return rand.Intn(max-min) + min
  83. }
  84. func GetToday(format string) string {
  85. today := time.Now().Format(format)
  86. return today
  87. }
  88. //获取今天剩余秒数
  89. func GetTodayLastSecond() time.Duration {
  90. today := GetToday(FormatDate) + " 23:59:59"
  91. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  92. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  93. }
  94. // 处理出生日期函数
  95. func GetBrithDate(idcard string) string {
  96. l := len(idcard)
  97. var s string
  98. if l == 15 {
  99. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  100. return s
  101. }
  102. if l == 18 {
  103. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  104. return s
  105. }
  106. return GetToday(FormatDate)
  107. }
  108. //处理性别
  109. func WhichSexByIdcard(idcard string) string {
  110. var sexs = [2]string{"女", "男"}
  111. length := len(idcard)
  112. if length == 18 {
  113. sex, _ := strconv.Atoi(string(idcard[16]))
  114. return sexs[sex%2]
  115. } else if length == 15 {
  116. sex, _ := strconv.Atoi(string(idcard[14]))
  117. return sexs[sex%2]
  118. }
  119. return "男"
  120. }
  121. //截取小数点后几位
  122. func SubFloatToString(f float64, m int) string {
  123. n := strconv.FormatFloat(f, 'f', -1, 64)
  124. if n == "" {
  125. return ""
  126. }
  127. if m >= len(n) {
  128. return n
  129. }
  130. newn := strings.Split(n, ".")
  131. if m == 0 {
  132. return newn[0]
  133. }
  134. if len(newn) < 2 || m >= len(newn[1]) {
  135. return n
  136. }
  137. return newn[0] + "." + newn[1][:m]
  138. }
  139. //截取小数点后几位
  140. func SubFloatToFloat(f float64, m int) float64 {
  141. newn := SubFloatToString(f, m)
  142. newf, _ := strconv.ParseFloat(newn, 64)
  143. return newf
  144. }
  145. //获取相差时间-年
  146. func GetYearDiffer(start_time, end_time string) int {
  147. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  148. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  149. age := t2.Year() - t1.Year()
  150. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  151. age--
  152. }
  153. return age
  154. }
  155. //获取相差时间-秒
  156. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  157. diff := end_time.Unix() - start_time.Unix()
  158. return diff
  159. }
  160. func FixFloat(f float64, m int) float64 {
  161. newn := SubFloatToString(f+0.00000001, m)
  162. newf, _ := strconv.ParseFloat(newn, 64)
  163. return newf
  164. }
  165. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  166. func StrListToString(strList []string) (str string) {
  167. if len(strList) > 0 {
  168. for k, v := range strList {
  169. if k == 0 {
  170. str = v
  171. } else {
  172. str = str + "," + v
  173. }
  174. }
  175. return
  176. }
  177. return ""
  178. }
  179. //Token
  180. func GetToken() string {
  181. randStr := GetRandString(64)
  182. token := MD5(randStr + Md5Key)
  183. tokenLen := 64 - len(token)
  184. return strings.ToUpper(token + GetRandString(tokenLen))
  185. }
  186. //数据没有记录
  187. func ErrNoRow() string {
  188. return "<QuerySeter> no row found"
  189. }
  190. //校验邮箱格式
  191. func ValidateEmailFormatat(email string) bool {
  192. reg := regexp.MustCompile(RegularEmail)
  193. return reg.MatchString(email)
  194. }
  195. //验证是否是手机号
  196. func ValidateMobileFormatat(mobileNum string) bool {
  197. reg := regexp.MustCompile(RegularMobile)
  198. return reg.MatchString(mobileNum)
  199. }
  200. //判断文件是否存在
  201. func FileIsExist(filePath string) bool {
  202. _, err := os.Stat(filePath)
  203. return err == nil || os.IsExist(err)
  204. }
  205. //获取图片扩展名
  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. //保存图片
  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. //保存base64数据为文件
  257. func SaveBase64ToFile(content, path string) error {
  258. data, err := base64.StdEncoding.DecodeString(content)
  259. if err != nil {
  260. return err
  261. }
  262. f, err := os.Create(path)
  263. defer f.Close()
  264. if err != nil {
  265. return err
  266. }
  267. f.Write(data)
  268. return nil
  269. }
  270. func SaveBase64ToFileBySeek(content, path string) (err error) {
  271. data, err := base64.StdEncoding.DecodeString(content)
  272. exist, err := PathExists(path)
  273. if err != nil {
  274. return
  275. }
  276. if !exist {
  277. f, err := os.Create(path)
  278. if err != nil {
  279. return err
  280. }
  281. n, _ := f.Seek(0, 2)
  282. // 从末尾的偏移量开始写入内容
  283. _, err = f.WriteAt([]byte(data), n)
  284. defer f.Close()
  285. } else {
  286. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  287. if err != nil {
  288. return err
  289. }
  290. n, _ := f.Seek(0, 2)
  291. // 从末尾的偏移量开始写入内容
  292. _, err = f.WriteAt([]byte(data), n)
  293. defer f.Close()
  294. }
  295. return nil
  296. }
  297. func PathExists(path string) (bool, error) {
  298. _, err := os.Stat(path)
  299. if err == nil {
  300. return true, nil
  301. }
  302. if os.IsNotExist(err) {
  303. return false, nil
  304. }
  305. return false, err
  306. }
  307. func StartIndex(page, pagesize int) int {
  308. if page > 1 {
  309. return (page - 1) * pagesize
  310. }
  311. return 0
  312. }
  313. func PageCount(count, pagesize int) int {
  314. if count%pagesize > 0 {
  315. return count/pagesize + 1
  316. } else {
  317. return count / pagesize
  318. }
  319. }
  320. func TrimHtml(src string) string {
  321. //将HTML标签全转换成小写
  322. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  323. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  324. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  325. src = re.ReplaceAllString(src, "[图片]")
  326. re, _ = regexp.Compile("class[\\S\\s]+?>")
  327. src = re.ReplaceAllString(src, "")
  328. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  329. src = re.ReplaceAllString(src, "")
  330. return strings.TrimSpace(src)
  331. }
  332. //1556164246 -> 2019-04-25 03:50:46 +0000
  333. //timestamp
  334. func TimeToTimestamp() {
  335. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  336. }
  337. func ToUnicode(text string) string {
  338. textQuoted := strconv.QuoteToASCII(text)
  339. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  340. return textUnquoted
  341. }
  342. func VersionToInt(version string) int {
  343. version = strings.Replace(version, ".", "", -1)
  344. n, _ := strconv.Atoi(version)
  345. return n
  346. }
  347. func IsCheckInList(list []int, s int) bool {
  348. for _, v := range list {
  349. if v == s {
  350. return true
  351. }
  352. }
  353. return false
  354. }
  355. func round(num float64) int {
  356. return int(num + math.Copysign(0.5, num))
  357. }
  358. func toFixed(num float64, precision int) float64 {
  359. output := math.Pow(10, float64(precision))
  360. return float64(round(num*output)) / output
  361. }
  362. // GetWilsonScore returns Wilson Score
  363. func GetWilsonScore(p, n float64) float64 {
  364. if p == 0 && n == 0 {
  365. return 0
  366. }
  367. 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)
  368. }
  369. //将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  370. func ChangeWordsToNum(str string) (numStr string) {
  371. words := ([]rune)(str)
  372. num := 0
  373. n := 0
  374. for i := 0; i < len(words); i++ {
  375. word := string(words[i : i+1])
  376. switch word {
  377. case "万":
  378. if n == 0 {
  379. n = 1
  380. }
  381. n = n * 10000
  382. num = num*10000 + n
  383. n = 0
  384. case "千":
  385. if n == 0 {
  386. n = 1
  387. }
  388. n = n * 1000
  389. num += n
  390. n = 0
  391. case "百":
  392. if n == 0 {
  393. n = 1
  394. }
  395. n = n * 100
  396. num += n
  397. n = 0
  398. case "十":
  399. if n == 0 {
  400. n = 1
  401. }
  402. n = n * 10
  403. num += n
  404. n = 0
  405. case "一":
  406. n += 1
  407. case "二":
  408. n += 2
  409. case "三":
  410. n += 3
  411. case "四":
  412. n += 4
  413. case "五":
  414. n += 5
  415. case "六":
  416. n += 6
  417. case "七":
  418. n += 7
  419. case "八":
  420. n += 8
  421. case "九":
  422. n += 9
  423. case "零":
  424. default:
  425. if n > 0 {
  426. num += n
  427. n = 0
  428. }
  429. if num == 0 {
  430. numStr += word
  431. } else {
  432. numStr += strconv.Itoa(num) + word
  433. num = 0
  434. }
  435. }
  436. }
  437. if n > 0 {
  438. num += n
  439. n = 0
  440. }
  441. if num != 0 {
  442. numStr += strconv.Itoa(num)
  443. }
  444. return
  445. }
  446. func Sha1(data string) string {
  447. sha1 := sha1.New()
  448. sha1.Write([]byte(data))
  449. return hex.EncodeToString(sha1.Sum([]byte("")))
  450. }
  451. func GetWeekDay() (weekStr string) {
  452. nowWeek := time.Now().Weekday().String()
  453. switch nowWeek {
  454. case "Monday":
  455. weekStr = "周一"
  456. break
  457. case "Tuesday":
  458. weekStr = "周二"
  459. break
  460. case "Wednesday":
  461. weekStr = "周三"
  462. break
  463. case "Thursday":
  464. weekStr = "周四"
  465. break
  466. case "Friday":
  467. weekStr = "周五"
  468. break
  469. case "Saturday":
  470. weekStr = "周六"
  471. break
  472. case "Sunday":
  473. weekStr = "周日"
  474. break
  475. default:
  476. weekStr = ""
  477. break
  478. }
  479. return
  480. }
  481. // GetNowWeekMonday 获取本周周一的时间
  482. func GetNowWeekMonday() time.Time {
  483. offset := int(time.Monday - time.Now().Weekday())
  484. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  485. offset = -6
  486. }
  487. mondayTime := time.Now().AddDate(0, 0, offset)
  488. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  489. return mondayTime
  490. }
  491. // GetNowWeekLastDay 获取本周最后一天的时间
  492. func GetNowWeekLastDay() time.Time {
  493. offset := int(time.Monday - time.Now().Weekday())
  494. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  495. offset = -6
  496. }
  497. firstDayTime := time.Now().AddDate(0, 0, offset)
  498. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  499. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  500. return lastDayTime
  501. }
  502. // GetNowMonthFirstDay 获取本月第一天的时间
  503. func GetNowMonthFirstDay() time.Time {
  504. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  505. return nowMonthFirstDay
  506. }
  507. // GetNowMonthLastDay 获取本月最后一天的时间
  508. func GetNowMonthLastDay() time.Time {
  509. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  510. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  511. return nowMonthLastDay
  512. }
  513. // GetNowQuarterFirstDay 获取本季度第一天的时间
  514. func GetNowQuarterFirstDay() time.Time {
  515. month := int(time.Now().Month())
  516. var nowQuarterFirstDay time.Time
  517. if month >= 1 && month <= 3 {
  518. //1月1号
  519. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  520. } else if month >= 4 && month <= 6 {
  521. //4月1号
  522. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  523. } else if month >= 7 && month <= 9 {
  524. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  525. } else {
  526. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  527. }
  528. return nowQuarterFirstDay
  529. }
  530. // GetNowQuarterLastDay 获取本季度最后一天的时间
  531. func GetNowQuarterLastDay() time.Time {
  532. month := int(time.Now().Month())
  533. var nowQuarterLastDay time.Time
  534. if month >= 1 && month <= 3 {
  535. //03-31 23:59:59
  536. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  537. } else if month >= 4 && month <= 6 {
  538. //06-30 23:59:59
  539. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  540. } else if month >= 7 && month <= 9 {
  541. //09-30 23:59:59
  542. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  543. } else {
  544. //12-31 23:59:59
  545. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  546. }
  547. return nowQuarterLastDay
  548. }
  549. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  550. func GetNowHalfYearFirstDay() time.Time {
  551. month := int(time.Now().Month())
  552. var nowHalfYearLastDay time.Time
  553. if month >= 1 && month <= 6 {
  554. //03-31 23:59:59
  555. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  556. } else {
  557. //12-31 23:59:59
  558. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  559. }
  560. return nowHalfYearLastDay
  561. }
  562. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  563. func GetNowHalfYearLastDay() time.Time {
  564. month := int(time.Now().Month())
  565. var nowHalfYearLastDay time.Time
  566. if month >= 1 && month <= 6 {
  567. //03-31 23:59:59
  568. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  569. } else {
  570. //12-31 23:59:59
  571. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  572. }
  573. return nowHalfYearLastDay
  574. }
  575. // GetNowYearFirstDay 获取当前年的最后一天的时间
  576. func GetNowYearFirstDay() time.Time {
  577. //12-31 23:59:59
  578. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  579. return nowYearFirstDay
  580. }
  581. // GetNowYearLastDay 获取当前年的最后一天的时间
  582. func GetNowYearLastDay() time.Time {
  583. //12-31 23:59:59
  584. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  585. return nowYearLastDay
  586. }
  587. // CalculationDate 计算两个日期之间相差n年m月y天
  588. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  589. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  590. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  591. numYear := endDate.Year() - startDate.Year()
  592. numMonth := int(endDate.Month()) - int(startDate.Month())
  593. numDay := 0
  594. //获取截止月的总天数
  595. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  596. //获取截止月的前一个月
  597. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  598. //获取截止日期的上一个月的总天数
  599. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  600. //获取开始日期的的月份总天数
  601. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  602. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  603. if endDate.Day() == endDateDays {
  604. numDay = startDateMonthDays - startDate.Day() + 1
  605. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  606. if numDay == startDateMonthDays {
  607. numMonth++
  608. numDay = 0
  609. //超过月份了,那么年份加1
  610. if numMonth == 12 {
  611. numYear++
  612. numMonth = 0
  613. }
  614. }
  615. } else {
  616. numDay = endDate.Day() - startDate.Day() + 1
  617. }
  618. //天数小于0,那么向月份借一位
  619. if numDay < 0 {
  620. //向上一个月借一个月的天数
  621. numDay += endDatePrevMonthDays
  622. //总月份减去一个月
  623. numMonth = numMonth - 1
  624. }
  625. //月份小于0,那么向年份借一位
  626. if numMonth < 0 {
  627. //向上一个年借12个月
  628. numMonth += 12
  629. //总年份减去一年
  630. numYear = numYear - 1
  631. }
  632. if numYear < 0 {
  633. err = errors.New("日期异常")
  634. return
  635. }
  636. if numYear > 0 {
  637. beetweenDay += fmt.Sprint(numYear, "年")
  638. }
  639. if numMonth > 0 {
  640. beetweenDay += fmt.Sprint(numMonth, "个月")
  641. }
  642. if numDay > 0 {
  643. beetweenDay += fmt.Sprint(numDay, "天")
  644. }
  645. return
  646. }
  647. // getMonthDay 获取某年某月有多少天
  648. func getMonthDay(year, month int) (days int) {
  649. if month != 2 {
  650. if month == 4 || month == 6 || month == 9 || month == 11 {
  651. days = 30
  652. } else {
  653. days = 31
  654. }
  655. } else {
  656. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  657. days = 29
  658. } else {
  659. days = 28
  660. }
  661. }
  662. return
  663. }
  664. // SubStr 截取字符串(中文)
  665. func SubStr(str string, subLen int) string {
  666. strRune := []rune(str)
  667. bodyRuneLen := len(strRune)
  668. if bodyRuneLen > subLen {
  669. bodyRuneLen = subLen
  670. }
  671. str = string(strRune[:bodyRuneLen])
  672. return str
  673. }
  674. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  675. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  676. for _, id := range idIntList {
  677. if id == searchId {
  678. has = true
  679. return
  680. }
  681. }
  682. return
  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. }