common.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. "net"
  16. "os"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. // 随机数种子
  23. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  24. func GetRandString(size int) string {
  25. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  26. randomSb := ""
  27. digitSize := len(allLetterDigit)
  28. for i := 0; i < size; i++ {
  29. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  30. }
  31. return randomSb
  32. }
  33. func GetRandStringNoSpecialChar(size int) string {
  34. 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"}
  35. randomSb := ""
  36. digitSize := len(allLetterDigit)
  37. for i := 0; i < size; i++ {
  38. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  39. }
  40. return randomSb
  41. }
  42. func StringsToJSON(str string) string {
  43. rs := []rune(str)
  44. jsons := ""
  45. for _, r := range rs {
  46. rint := int(r)
  47. if rint < 128 {
  48. jsons += string(r)
  49. } else {
  50. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  51. }
  52. }
  53. return jsons
  54. }
  55. // 序列化
  56. func ToString(v interface{}) string {
  57. data, _ := json.Marshal(v)
  58. return string(data)
  59. }
  60. // md5加密
  61. func MD5(data string) string {
  62. m := md5.Sum([]byte(data))
  63. return hex.EncodeToString(m[:])
  64. }
  65. // HmacMd5 HmacMd5加密
  66. func HmacMd5(key, data string) string {
  67. h := hmac.New(md5.New, []byte(key))
  68. h.Write([]byte(data))
  69. return hex.EncodeToString(h.Sum([]byte("")))
  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 GetYearDiffer(start_time, end_time string) int {
  148. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  149. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  150. age := t2.Year() - t1.Year()
  151. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  152. age--
  153. }
  154. return age
  155. }
  156. // 获取相差时间-秒
  157. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  158. diff := end_time.Unix() - start_time.Unix()
  159. return diff
  160. }
  161. func FixFloat(f float64, m int) float64 {
  162. newn := SubFloatToString(f+0.00000001, m)
  163. newf, _ := strconv.ParseFloat(newn, 64)
  164. return newf
  165. }
  166. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  167. func StrListToString(strList []string) (str string) {
  168. if len(strList) > 0 {
  169. for k, v := range strList {
  170. if k == 0 {
  171. str = v
  172. } else {
  173. str = str + "," + v
  174. }
  175. }
  176. return
  177. }
  178. return ""
  179. }
  180. // 数据没有记录
  181. func ErrNoRow() string {
  182. return "<QuerySeter> no row found"
  183. }
  184. // 校验邮箱格式
  185. func ValidateEmailFormatat(email string) bool {
  186. reg := regexp.MustCompile(RegularEmail)
  187. return reg.MatchString(email)
  188. }
  189. // 验证是否是手机号
  190. func ValidateMobileFormatat(mobileNum string) bool {
  191. reg := regexp.MustCompile(RegularMobile)
  192. return reg.MatchString(mobileNum)
  193. }
  194. // 判断文件是否存在
  195. func FileIsExist(filePath string) bool {
  196. _, err := os.Stat(filePath)
  197. return err == nil || os.IsExist(err)
  198. }
  199. // 获取图片扩展名
  200. func GetImgExt(file string) (ext string, err error) {
  201. var headerByte []byte
  202. headerByte = make([]byte, 8)
  203. fd, err := os.Open(file)
  204. if err != nil {
  205. return "", err
  206. }
  207. defer fd.Close()
  208. _, err = fd.Read(headerByte)
  209. if err != nil {
  210. return "", err
  211. }
  212. xStr := fmt.Sprintf("%x", headerByte)
  213. switch {
  214. case xStr == "89504e470d0a1a0a":
  215. ext = ".png"
  216. case xStr == "0000010001002020":
  217. ext = ".ico"
  218. case xStr == "0000020001002020":
  219. ext = ".cur"
  220. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  221. ext = ".gif"
  222. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  223. ext = ".tga"
  224. case xStr[:8] == "464f524d":
  225. ext = ".iff"
  226. case xStr[:8] == "52494646":
  227. ext = ".ani"
  228. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  229. ext = ".tiff"
  230. case xStr[:4] == "424d":
  231. ext = ".bmp"
  232. case xStr[:4] == "ffd8":
  233. ext = ".jpg"
  234. case xStr[:2] == "0a":
  235. ext = ".pcx"
  236. default:
  237. ext = ""
  238. }
  239. return ext, nil
  240. }
  241. // 保存图片
  242. func SaveImage(path string, img image.Image) (err error) {
  243. //需要保持的文件
  244. imgfile, err := os.Create(path)
  245. defer imgfile.Close()
  246. // 以PNG格式保存文件
  247. err = png.Encode(imgfile, img)
  248. return err
  249. }
  250. // 保存base64数据为文件
  251. func SaveBase64ToFile(content, path string) error {
  252. data, err := base64.StdEncoding.DecodeString(content)
  253. if err != nil {
  254. return err
  255. }
  256. f, err := os.Create(path)
  257. defer f.Close()
  258. if err != nil {
  259. return err
  260. }
  261. f.Write(data)
  262. return nil
  263. }
  264. func SaveBase64ToFileBySeek(content, path string) (err error) {
  265. data, err := base64.StdEncoding.DecodeString(content)
  266. exist, err := PathExists(path)
  267. if err != nil {
  268. return
  269. }
  270. if !exist {
  271. f, err := os.Create(path)
  272. if err != nil {
  273. return err
  274. }
  275. n, _ := f.Seek(0, 2)
  276. // 从末尾的偏移量开始写入内容
  277. _, err = f.WriteAt([]byte(data), n)
  278. defer f.Close()
  279. } else {
  280. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  281. if err != nil {
  282. return err
  283. }
  284. n, _ := f.Seek(0, 2)
  285. // 从末尾的偏移量开始写入内容
  286. _, err = f.WriteAt([]byte(data), n)
  287. defer f.Close()
  288. }
  289. return nil
  290. }
  291. func PathExists(path string) (bool, error) {
  292. _, err := os.Stat(path)
  293. if err == nil {
  294. return true, nil
  295. }
  296. if os.IsNotExist(err) {
  297. return false, nil
  298. }
  299. return false, err
  300. }
  301. func StartIndex(page, pagesize int) int {
  302. if page > 1 {
  303. return (page - 1) * pagesize
  304. }
  305. return 0
  306. }
  307. func PageCount(count, pagesize int) int {
  308. if count%pagesize > 0 {
  309. return count/pagesize + 1
  310. } else {
  311. return count / pagesize
  312. }
  313. }
  314. func TrimHtml(src string) string {
  315. //将HTML标签全转换成小写
  316. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  317. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  318. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  319. src = re.ReplaceAllString(src, "[图片]")
  320. re, _ = regexp.Compile("class[\\S\\s]+?>")
  321. src = re.ReplaceAllString(src, "")
  322. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  323. src = re.ReplaceAllString(src, "")
  324. return strings.TrimSpace(src)
  325. }
  326. //1556164246 -> 2019-04-25 03:50:46 +0000
  327. //timestamp
  328. func TimeToTimestamp() {
  329. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  330. }
  331. func ToUnicode(text string) string {
  332. textQuoted := strconv.QuoteToASCII(text)
  333. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  334. return textUnquoted
  335. }
  336. func VersionToInt(version string) int {
  337. version = strings.Replace(version, ".", "", -1)
  338. n, _ := strconv.Atoi(version)
  339. return n
  340. }
  341. func IsCheckInList(list []int, s int) bool {
  342. for _, v := range list {
  343. if v == s {
  344. return true
  345. }
  346. }
  347. return false
  348. }
  349. func round(num float64) int {
  350. return int(num + math.Copysign(0.5, num))
  351. }
  352. func toFixed(num float64, precision int) float64 {
  353. output := math.Pow(10, float64(precision))
  354. return float64(round(num*output)) / output
  355. }
  356. // GetWilsonScore returns Wilson Score
  357. func GetWilsonScore(p, n float64) float64 {
  358. if p == 0 && n == 0 {
  359. return 0
  360. }
  361. 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)
  362. }
  363. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  364. func ChangeWordsToNum(str string) (numStr string) {
  365. words := ([]rune)(str)
  366. num := 0
  367. n := 0
  368. for i := 0; i < len(words); i++ {
  369. word := string(words[i : i+1])
  370. switch word {
  371. case "万":
  372. if n == 0 {
  373. n = 1
  374. }
  375. n = n * 10000
  376. num = num*10000 + n
  377. n = 0
  378. case "千":
  379. if n == 0 {
  380. n = 1
  381. }
  382. n = n * 1000
  383. num += n
  384. n = 0
  385. case "百":
  386. if n == 0 {
  387. n = 1
  388. }
  389. n = n * 100
  390. num += n
  391. n = 0
  392. case "十":
  393. if n == 0 {
  394. n = 1
  395. }
  396. n = n * 10
  397. num += n
  398. n = 0
  399. case "一":
  400. n += 1
  401. case "二":
  402. n += 2
  403. case "三":
  404. n += 3
  405. case "四":
  406. n += 4
  407. case "五":
  408. n += 5
  409. case "六":
  410. n += 6
  411. case "七":
  412. n += 7
  413. case "八":
  414. n += 8
  415. case "九":
  416. n += 9
  417. case "零":
  418. default:
  419. if n > 0 {
  420. num += n
  421. n = 0
  422. }
  423. if num == 0 {
  424. numStr += word
  425. } else {
  426. numStr += strconv.Itoa(num) + word
  427. num = 0
  428. }
  429. }
  430. }
  431. if n > 0 {
  432. num += n
  433. n = 0
  434. }
  435. if num != 0 {
  436. numStr += strconv.Itoa(num)
  437. }
  438. return
  439. }
  440. func Sha1(data string) string {
  441. sha1 := sha1.New()
  442. sha1.Write([]byte(data))
  443. return hex.EncodeToString(sha1.Sum([]byte("")))
  444. }
  445. func GetWeekDay() (weekStr string) {
  446. nowWeek := time.Now().Weekday().String()
  447. switch nowWeek {
  448. case "Monday":
  449. weekStr = "周一"
  450. break
  451. case "Tuesday":
  452. weekStr = "周二"
  453. break
  454. case "Wednesday":
  455. weekStr = "周三"
  456. break
  457. case "Thursday":
  458. weekStr = "周四"
  459. break
  460. case "Friday":
  461. weekStr = "周五"
  462. break
  463. case "Saturday":
  464. weekStr = "周六"
  465. break
  466. case "Sunday":
  467. weekStr = "周日"
  468. break
  469. default:
  470. weekStr = ""
  471. break
  472. }
  473. return
  474. }
  475. // GetNowWeekMonday 获取本周周一的时间
  476. func GetNowWeekMonday() time.Time {
  477. offset := int(time.Monday - time.Now().Weekday())
  478. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  479. offset = -6
  480. }
  481. mondayTime := time.Now().AddDate(0, 0, offset)
  482. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  483. return mondayTime
  484. }
  485. // GetLastWeekMonday 获取上周周一的时间
  486. func GetLastWeekMonday() time.Time {
  487. offset := int(time.Monday - time.Now().Weekday())
  488. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  489. offset = -6
  490. }
  491. mondayTime := time.Now().AddDate(0, 0, offset-7)
  492. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  493. return mondayTime
  494. }
  495. // GetNowWeekTuesday 获取本周周二的时间
  496. func GetNowWeekTuesday() time.Time {
  497. offset := int(time.Tuesday - time.Now().Weekday())
  498. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  499. offset = -6
  500. }
  501. mondayTime := time.Now().AddDate(0, 0, offset)
  502. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  503. return mondayTime
  504. }
  505. // GetLastWeekTuesday 获取上周周二的时间
  506. func GetLastWeekTuesday() time.Time {
  507. offset := int(time.Tuesday - time.Now().Weekday())
  508. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  509. offset = -6
  510. }
  511. mondayTime := time.Now().AddDate(0, 0, offset-7)
  512. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  513. return mondayTime
  514. }
  515. // GetNowWeekFriday 获取本周周四的时间
  516. func GetNowWeekThursday() time.Time {
  517. offset := int(time.Thursday - time.Now().Weekday())
  518. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  519. offset = -6
  520. }
  521. fridayTime := time.Now().AddDate(0, 0, offset)
  522. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  523. return fridayTime
  524. }
  525. // GetLastWeekFriday 获取上周周四的时间
  526. func GetLastWeekThursday() time.Time {
  527. offset := int(time.Thursday - time.Now().Weekday())
  528. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  529. offset = -6
  530. }
  531. fridayTime := time.Now().AddDate(0, 0, offset-7)
  532. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  533. return fridayTime
  534. }
  535. // GetNowWeekFriday 获取本周周五的时间
  536. func GetNowWeekFriday() time.Time {
  537. offset := int(time.Friday - time.Now().Weekday())
  538. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  539. offset = -6
  540. }
  541. fridayTime := time.Now().AddDate(0, 0, offset)
  542. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  543. return fridayTime
  544. }
  545. // GetLastWeekFriday 获取上周周五的时间
  546. func GetLastWeekFriday() time.Time {
  547. offset := int(time.Friday - time.Now().Weekday())
  548. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  549. offset = -6
  550. }
  551. fridayTime := time.Now().AddDate(0, 0, offset-7)
  552. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  553. return fridayTime
  554. }
  555. // GetNowWeekLastDay 获取本周最后一天的时间
  556. func GetNowWeekLastDay() time.Time {
  557. offset := int(time.Monday - time.Now().Weekday())
  558. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  559. offset = -6
  560. }
  561. firstDayTime := time.Now().AddDate(0, 0, offset)
  562. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  563. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  564. return lastDayTime
  565. }
  566. // GetNowMonthFirstDay 获取本月第一天的时间
  567. func GetNowMonthFirstDay() time.Time {
  568. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  569. return nowMonthFirstDay
  570. }
  571. // GetNowMonthLastDay 获取本月最后一天的时间
  572. func GetNowMonthLastDay() time.Time {
  573. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  574. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  575. return nowMonthLastDay
  576. }
  577. // GetNowQuarterFirstDay 获取本季度第一天的时间
  578. func GetNowQuarterFirstDay() time.Time {
  579. month := int(time.Now().Month())
  580. var nowQuarterFirstDay time.Time
  581. if month >= 1 && month <= 3 {
  582. //1月1号
  583. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  584. } else if month >= 4 && month <= 6 {
  585. //4月1号
  586. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  587. } else if month >= 7 && month <= 9 {
  588. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  589. } else {
  590. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  591. }
  592. return nowQuarterFirstDay
  593. }
  594. // GetNowQuarterLastDay 获取本季度最后一天的时间
  595. func GetNowQuarterLastDay() time.Time {
  596. month := int(time.Now().Month())
  597. var nowQuarterLastDay time.Time
  598. if month >= 1 && month <= 3 {
  599. //03-31 23:59:59
  600. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  601. } else if month >= 4 && month <= 6 {
  602. //06-30 23:59:59
  603. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  604. } else if month >= 7 && month <= 9 {
  605. //09-30 23:59:59
  606. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  607. } else {
  608. //12-31 23:59:59
  609. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  610. }
  611. return nowQuarterLastDay
  612. }
  613. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  614. func GetNowHalfYearFirstDay() time.Time {
  615. month := int(time.Now().Month())
  616. var nowHalfYearLastDay time.Time
  617. if month >= 1 && month <= 6 {
  618. //03-31 23:59:59
  619. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  620. } else {
  621. //12-31 23:59:59
  622. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  623. }
  624. return nowHalfYearLastDay
  625. }
  626. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  627. func GetNowHalfYearLastDay() time.Time {
  628. month := int(time.Now().Month())
  629. var nowHalfYearLastDay time.Time
  630. if month >= 1 && month <= 6 {
  631. //03-31 23:59:59
  632. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  633. } else {
  634. //12-31 23:59:59
  635. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  636. }
  637. return nowHalfYearLastDay
  638. }
  639. // GetNowYearFirstDay 获取当前年的最后一天的时间
  640. func GetNowYearFirstDay() time.Time {
  641. //12-31 23:59:59
  642. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  643. return nowYearFirstDay
  644. }
  645. // GetNowYearLastDay 获取当前年的最后一天的时间
  646. func GetNowYearLastDay() time.Time {
  647. //12-31 23:59:59
  648. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  649. return nowYearLastDay
  650. }
  651. // CalculationDate 计算两个日期之间相差n年m月y天
  652. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  653. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  654. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  655. numYear := endDate.Year() - startDate.Year()
  656. numMonth := int(endDate.Month()) - int(startDate.Month())
  657. numDay := 0
  658. //获取截止月的总天数
  659. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  660. //获取截止月的前一个月
  661. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  662. //获取截止日期的上一个月的总天数
  663. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  664. //获取开始日期的的月份总天数
  665. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  666. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  667. if endDate.Day() == endDateDays {
  668. numDay = startDateMonthDays - startDate.Day() + 1
  669. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  670. if numDay == startDateMonthDays {
  671. numMonth++
  672. numDay = 0
  673. //超过月份了,那么年份加1
  674. if numMonth == 12 {
  675. numYear++
  676. numMonth = 0
  677. }
  678. }
  679. } else {
  680. numDay = endDate.Day() - startDate.Day() + 1
  681. }
  682. //天数小于0,那么向月份借一位
  683. if numDay < 0 {
  684. //向上一个月借一个月的天数
  685. numDay += endDatePrevMonthDays
  686. //总月份减去一个月
  687. numMonth = numMonth - 1
  688. }
  689. //月份小于0,那么向年份借一位
  690. if numMonth < 0 {
  691. //向上一个年借12个月
  692. numMonth += 12
  693. //总年份减去一年
  694. numYear = numYear - 1
  695. }
  696. if numYear < 0 {
  697. err = errors.New("日期异常")
  698. return
  699. }
  700. if numYear > 0 {
  701. beetweenDay += fmt.Sprint(numYear, "年")
  702. }
  703. if numMonth > 0 {
  704. beetweenDay += fmt.Sprint(numMonth, "个月")
  705. }
  706. if numDay > 0 {
  707. beetweenDay += fmt.Sprint(numDay, "天")
  708. }
  709. return
  710. }
  711. // getMonthDay 获取某年某月有多少天
  712. func getMonthDay(year, month int) (days int) {
  713. if month != 2 {
  714. if month == 4 || month == 6 || month == 9 || month == 11 {
  715. days = 30
  716. } else {
  717. days = 31
  718. }
  719. } else {
  720. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  721. days = 29
  722. } else {
  723. days = 28
  724. }
  725. }
  726. return
  727. }
  728. // SubStr 截取字符串(中文)
  729. func SubStr(str string, subLen int) string {
  730. strRune := []rune(str)
  731. bodyRuneLen := len(strRune)
  732. if bodyRuneLen > subLen {
  733. bodyRuneLen = subLen
  734. }
  735. str = string(strRune[:bodyRuneLen])
  736. return str
  737. }
  738. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  739. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  740. for _, id := range idIntList {
  741. if id == searchId {
  742. has = true
  743. return
  744. }
  745. }
  746. return
  747. }
  748. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  749. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  750. for _, id := range idStrList {
  751. if id == searchId {
  752. has = true
  753. return
  754. }
  755. }
  756. return
  757. }
  758. func GetLocalIP() (ip string, err error) {
  759. addrs, err := net.InterfaceAddrs()
  760. if err != nil {
  761. return
  762. }
  763. for _, addr := range addrs {
  764. ipAddr, ok := addr.(*net.IPNet)
  765. if !ok {
  766. continue
  767. }
  768. if ipAddr.IP.IsLoopback() {
  769. continue
  770. }
  771. if !ipAddr.IP.IsGlobalUnicast() {
  772. continue
  773. }
  774. return ipAddr.IP.String(), nil
  775. }
  776. return
  777. }
  778. // 富文本字段过滤处理
  779. func GetRichText(content string) (contentSub string) {
  780. contentSub = strings.Replace(content, "<p data-f-id=\"pbf\" style=\"text-align: center; font-size: 14px; margin-top: 30px; opacity: 0.65; font-family: sans-serif;\">Powered by <a href=\"https://www.froala.com/wysiwyg-editor?pb=1\" title=\"Froala Editor\">Froala Editor</a></p>", "", -1)
  781. return
  782. }
  783. // GetOrmInReplace 获取orm的in查询替换?的方法
  784. func GetOrmInReplace(num int) string {
  785. template := make([]string, num)
  786. for i := 0; i < num; i++ {
  787. template[i] = "?"
  788. }
  789. return strings.Join(template, ",")
  790. }