common.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. package utils
  2. import (
  3. "crypto/hmac"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "image"
  13. "image/png"
  14. "math"
  15. "math/rand"
  16. "net"
  17. "os"
  18. "os/exec"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. // 随机数种子
  25. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  26. func GetRandString(size int) string {
  27. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  28. randomSb := ""
  29. digitSize := len(allLetterDigit)
  30. for i := 0; i < size; i++ {
  31. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  32. }
  33. return randomSb
  34. }
  35. func GetRandStringNoSpecialChar(size int) string {
  36. 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"}
  37. randomSb := ""
  38. digitSize := len(allLetterDigit)
  39. for i := 0; i < size; i++ {
  40. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  41. }
  42. return randomSb
  43. }
  44. func StringsToJSON(str string) string {
  45. rs := []rune(str)
  46. jsons := ""
  47. for _, r := range rs {
  48. rint := int(r)
  49. if rint < 128 {
  50. jsons += string(r)
  51. } else {
  52. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  53. }
  54. }
  55. return jsons
  56. }
  57. // 序列化
  58. func ToString(v interface{}) string {
  59. data, _ := json.Marshal(v)
  60. return string(data)
  61. }
  62. // md5加密
  63. func MD5(data string) string {
  64. m := md5.Sum([]byte(data))
  65. return hex.EncodeToString(m[:])
  66. }
  67. // HmacMd5 HmacMd5加密
  68. func HmacMd5(key, data string) string {
  69. h := hmac.New(md5.New, []byte(key))
  70. h.Write([]byte(data))
  71. return hex.EncodeToString(h.Sum([]byte("")))
  72. }
  73. // 获取数字随机字符
  74. func GetRandDigit(n int) string {
  75. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  76. }
  77. // 获取随机数
  78. func GetRandNumber(n int) int {
  79. return rnd.Intn(n)
  80. }
  81. func GetRandInt(min, max int) int {
  82. if min >= max || min == 0 || max == 0 {
  83. return max
  84. }
  85. return rand.Intn(max-min) + min
  86. }
  87. func GetToday(format string) string {
  88. today := time.Now().Format(format)
  89. return today
  90. }
  91. // 获取今天剩余秒数
  92. func GetTodayLastSecond() time.Duration {
  93. today := GetToday(FormatDate) + " 23:59:59"
  94. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  95. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  96. }
  97. // 处理出生日期函数
  98. func GetBrithDate(idcard string) string {
  99. l := len(idcard)
  100. var s string
  101. if l == 15 {
  102. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  103. return s
  104. }
  105. if l == 18 {
  106. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  107. return s
  108. }
  109. return GetToday(FormatDate)
  110. }
  111. // 处理性别
  112. func WhichSexByIdcard(idcard string) string {
  113. var sexs = [2]string{"女", "男"}
  114. length := len(idcard)
  115. if length == 18 {
  116. sex, _ := strconv.Atoi(string(idcard[16]))
  117. return sexs[sex%2]
  118. } else if length == 15 {
  119. sex, _ := strconv.Atoi(string(idcard[14]))
  120. return sexs[sex%2]
  121. }
  122. return "男"
  123. }
  124. // 截取小数点后几位
  125. func SubFloatToString(f float64, m int) string {
  126. n := strconv.FormatFloat(f, 'f', -1, 64)
  127. if n == "" {
  128. return ""
  129. }
  130. if m >= len(n) {
  131. return n
  132. }
  133. newn := strings.Split(n, ".")
  134. if m == 0 {
  135. return newn[0]
  136. }
  137. if len(newn) < 2 || m >= len(newn[1]) {
  138. return n
  139. }
  140. return newn[0] + "." + newn[1][:m]
  141. }
  142. // 截取小数点后几位
  143. func SubFloatToFloat(f float64, m int) float64 {
  144. newn := SubFloatToString(f, m)
  145. newf, _ := strconv.ParseFloat(newn, 64)
  146. return newf
  147. }
  148. // 获取相差时间-年
  149. func GetYearDiffer(start_time, end_time string) int {
  150. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  151. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  152. age := t2.Year() - t1.Year()
  153. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  154. age--
  155. }
  156. return age
  157. }
  158. // 获取相差时间-秒
  159. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  160. diff := end_time.Unix() - start_time.Unix()
  161. return diff
  162. }
  163. func FixFloat(f float64, m int) float64 {
  164. newn := SubFloatToString(f+0.00000001, m)
  165. newf, _ := strconv.ParseFloat(newn, 64)
  166. return newf
  167. }
  168. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  169. func StrListToString(strList []string) (str string) {
  170. if len(strList) > 0 {
  171. for k, v := range strList {
  172. if k == 0 {
  173. str = v
  174. } else {
  175. str = str + "," + v
  176. }
  177. }
  178. return
  179. }
  180. return ""
  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 GetWeekDay() (weekStr string) {
  448. nowWeek := time.Now().Weekday().String()
  449. switch nowWeek {
  450. case "Monday":
  451. weekStr = "周一"
  452. break
  453. case "Tuesday":
  454. weekStr = "周二"
  455. break
  456. case "Wednesday":
  457. weekStr = "周三"
  458. break
  459. case "Thursday":
  460. weekStr = "周四"
  461. break
  462. case "Friday":
  463. weekStr = "周五"
  464. break
  465. case "Saturday":
  466. weekStr = "周六"
  467. break
  468. case "Sunday":
  469. weekStr = "周日"
  470. break
  471. default:
  472. weekStr = ""
  473. break
  474. }
  475. return
  476. }
  477. // GetNowWeekMonday 获取本周周一的时间
  478. func GetNowWeekMonday() time.Time {
  479. offset := int(time.Monday - time.Now().Weekday())
  480. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  481. offset = -6
  482. }
  483. mondayTime := time.Now().AddDate(0, 0, offset)
  484. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  485. return mondayTime
  486. }
  487. // GetLastWeekMonday 获取上周周一的时间
  488. func GetLastWeekMonday() time.Time {
  489. offset := int(time.Monday - time.Now().Weekday())
  490. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  491. offset = -6
  492. }
  493. mondayTime := time.Now().AddDate(0, 0, offset-7)
  494. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  495. return mondayTime
  496. }
  497. // GetNowWeekTuesday 获取本周周二的时间
  498. func GetNowWeekTuesday() time.Time {
  499. offset := int(time.Tuesday - time.Now().Weekday())
  500. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  501. offset = -6
  502. }
  503. mondayTime := time.Now().AddDate(0, 0, offset)
  504. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  505. return mondayTime
  506. }
  507. // GetLastWeekTuesday 获取上周周二的时间
  508. func GetLastWeekTuesday() time.Time {
  509. offset := int(time.Tuesday - time.Now().Weekday())
  510. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  511. offset = -6
  512. }
  513. mondayTime := time.Now().AddDate(0, 0, offset-7)
  514. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  515. return mondayTime
  516. }
  517. // GetNowWeekFriday 获取本周周四的时间
  518. func GetNowWeekThursday() time.Time {
  519. offset := int(time.Thursday - time.Now().Weekday())
  520. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  521. offset = -6
  522. }
  523. fridayTime := time.Now().AddDate(0, 0, offset)
  524. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  525. return fridayTime
  526. }
  527. // GetLastWeekFriday 获取上周周四的时间
  528. func GetLastWeekThursday() time.Time {
  529. offset := int(time.Thursday - time.Now().Weekday())
  530. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  531. offset = -6
  532. }
  533. fridayTime := time.Now().AddDate(0, 0, offset-7)
  534. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  535. return fridayTime
  536. }
  537. // GetNowWeekFriday 获取本周周五的时间
  538. func GetNowWeekFriday() time.Time {
  539. offset := int(time.Friday - time.Now().Weekday())
  540. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  541. offset = -6
  542. }
  543. fridayTime := time.Now().AddDate(0, 0, offset)
  544. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  545. return fridayTime
  546. }
  547. // GetLastWeekFriday 获取上周周五的时间
  548. func GetLastWeekFriday() time.Time {
  549. offset := int(time.Friday - time.Now().Weekday())
  550. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  551. offset = -6
  552. }
  553. fridayTime := time.Now().AddDate(0, 0, offset-7)
  554. fridayTime = time.Date(fridayTime.Year(), fridayTime.Month(), fridayTime.Day(), 0, 0, 0, 0, fridayTime.Location())
  555. return fridayTime
  556. }
  557. // GetNowWeekLastDay 获取本周最后一天的时间
  558. func GetNowWeekLastDay() time.Time {
  559. offset := int(time.Monday - time.Now().Weekday())
  560. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  561. offset = -6
  562. }
  563. firstDayTime := time.Now().AddDate(0, 0, offset)
  564. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  565. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  566. return lastDayTime
  567. }
  568. // GetNowMonthFirstDay 获取本月第一天的时间
  569. func GetNowMonthFirstDay() time.Time {
  570. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  571. return nowMonthFirstDay
  572. }
  573. // GetNowMonthLastDay 获取本月最后一天的时间
  574. func GetNowMonthLastDay() time.Time {
  575. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  576. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  577. return nowMonthLastDay
  578. }
  579. // GetNowQuarterFirstDay 获取本季度第一天的时间
  580. func GetNowQuarterFirstDay() time.Time {
  581. month := int(time.Now().Month())
  582. var nowQuarterFirstDay time.Time
  583. if month >= 1 && month <= 3 {
  584. //1月1号
  585. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  586. } else if month >= 4 && month <= 6 {
  587. //4月1号
  588. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  589. } else if month >= 7 && month <= 9 {
  590. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  591. } else {
  592. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  593. }
  594. return nowQuarterFirstDay
  595. }
  596. // GetNowQuarterLastDay 获取本季度最后一天的时间
  597. func GetNowQuarterLastDay() time.Time {
  598. month := int(time.Now().Month())
  599. var nowQuarterLastDay time.Time
  600. if month >= 1 && month <= 3 {
  601. //03-31 23:59:59
  602. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  603. } else if month >= 4 && month <= 6 {
  604. //06-30 23:59:59
  605. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  606. } else if month >= 7 && month <= 9 {
  607. //09-30 23:59:59
  608. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  609. } else {
  610. //12-31 23:59:59
  611. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  612. }
  613. return nowQuarterLastDay
  614. }
  615. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  616. func GetNowHalfYearFirstDay() time.Time {
  617. month := int(time.Now().Month())
  618. var nowHalfYearLastDay time.Time
  619. if month >= 1 && month <= 6 {
  620. //03-31 23:59:59
  621. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  622. } else {
  623. //12-31 23:59:59
  624. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  625. }
  626. return nowHalfYearLastDay
  627. }
  628. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  629. func GetNowHalfYearLastDay() time.Time {
  630. month := int(time.Now().Month())
  631. var nowHalfYearLastDay time.Time
  632. if month >= 1 && month <= 6 {
  633. //03-31 23:59:59
  634. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  635. } else {
  636. //12-31 23:59:59
  637. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  638. }
  639. return nowHalfYearLastDay
  640. }
  641. // GetNowYearFirstDay 获取当前年的最后一天的时间
  642. func GetNowYearFirstDay() time.Time {
  643. //12-31 23:59:59
  644. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  645. return nowYearFirstDay
  646. }
  647. // GetNowYearLastDay 获取当前年的最后一天的时间
  648. func GetNowYearLastDay() time.Time {
  649. //12-31 23:59:59
  650. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  651. return nowYearLastDay
  652. }
  653. // CalculationDate 计算两个日期之间相差n年m月y天
  654. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  655. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  656. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  657. numYear := endDate.Year() - startDate.Year()
  658. numMonth := int(endDate.Month()) - int(startDate.Month())
  659. numDay := 0
  660. //获取截止月的总天数
  661. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  662. //获取截止月的前一个月
  663. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  664. //获取截止日期的上一个月的总天数
  665. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  666. //获取开始日期的的月份总天数
  667. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  668. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  669. if endDate.Day() == endDateDays {
  670. numDay = startDateMonthDays - startDate.Day() + 1
  671. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  672. if numDay == startDateMonthDays {
  673. numMonth++
  674. numDay = 0
  675. //超过月份了,那么年份加1
  676. if numMonth == 12 {
  677. numYear++
  678. numMonth = 0
  679. }
  680. }
  681. } else {
  682. numDay = endDate.Day() - startDate.Day() + 1
  683. }
  684. //天数小于0,那么向月份借一位
  685. if numDay < 0 {
  686. //向上一个月借一个月的天数
  687. numDay += endDatePrevMonthDays
  688. //总月份减去一个月
  689. numMonth = numMonth - 1
  690. }
  691. //月份小于0,那么向年份借一位
  692. if numMonth < 0 {
  693. //向上一个年借12个月
  694. numMonth += 12
  695. //总年份减去一年
  696. numYear = numYear - 1
  697. }
  698. if numYear < 0 {
  699. err = errors.New("日期异常")
  700. return
  701. }
  702. if numYear > 0 {
  703. beetweenDay += fmt.Sprint(numYear, "年")
  704. }
  705. if numMonth > 0 {
  706. beetweenDay += fmt.Sprint(numMonth, "个月")
  707. }
  708. if numDay > 0 {
  709. beetweenDay += fmt.Sprint(numDay, "天")
  710. }
  711. return
  712. }
  713. // getMonthDay 获取某年某月有多少天
  714. func getMonthDay(year, month int) (days int) {
  715. if month != 2 {
  716. if month == 4 || month == 6 || month == 9 || month == 11 {
  717. days = 30
  718. } else {
  719. days = 31
  720. }
  721. } else {
  722. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  723. days = 29
  724. } else {
  725. days = 28
  726. }
  727. }
  728. return
  729. }
  730. // SubStr 截取字符串(中文)
  731. func SubStr(str string, subLen int) string {
  732. strRune := []rune(str)
  733. bodyRuneLen := len(strRune)
  734. if bodyRuneLen > subLen {
  735. bodyRuneLen = subLen
  736. }
  737. str = string(strRune[:bodyRuneLen])
  738. return str
  739. }
  740. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  741. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  742. for _, id := range idIntList {
  743. if id == searchId {
  744. has = true
  745. return
  746. }
  747. }
  748. return
  749. }
  750. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  751. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  752. for _, id := range idStrList {
  753. if id == searchId {
  754. has = true
  755. return
  756. }
  757. }
  758. return
  759. }
  760. func GetLocalIP() (ip string, err error) {
  761. addrs, err := net.InterfaceAddrs()
  762. if err != nil {
  763. return
  764. }
  765. for _, addr := range addrs {
  766. ipAddr, ok := addr.(*net.IPNet)
  767. if !ok {
  768. continue
  769. }
  770. if ipAddr.IP.IsLoopback() {
  771. continue
  772. }
  773. if !ipAddr.IP.IsGlobalUnicast() {
  774. continue
  775. }
  776. return ipAddr.IP.String(), nil
  777. }
  778. return
  779. }
  780. // 富文本字段过滤处理
  781. func GetRichText(content string) (contentSub string) {
  782. 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)
  783. return
  784. }
  785. // GetOrmInReplace 获取orm的in查询替换?的方法
  786. func GetOrmInReplace(num int) string {
  787. template := make([]string, num)
  788. for i := 0; i < num; i++ {
  789. template[i] = "?"
  790. }
  791. return strings.Join(template, ",")
  792. }
  793. // SubFloatToFloatStr 截取小数点后几位
  794. func SubFloatToFloatStr(f float64, m int) string {
  795. newn := SubFloatToString(f, m)
  796. return newn
  797. }
  798. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  799. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  800. out, err := exec.Command("bash", "-c", cmd).Output()
  801. if err != nil {
  802. return
  803. }
  804. outTimes := string(out)
  805. fmt.Println("outTimes:", outTimes)
  806. if outTimes != "" {
  807. timeArr := strings.Split(outTimes, ":")
  808. h := timeArr[0]
  809. m := timeArr[1]
  810. s := timeArr[2]
  811. hInt, err := strconv.Atoi(h)
  812. if err != nil {
  813. return playSeconds, err
  814. }
  815. mInt, err := strconv.Atoi(m)
  816. if err != nil {
  817. return playSeconds, err
  818. }
  819. s = strings.Trim(s, " ")
  820. s = strings.Trim(s, "\n")
  821. sInt, err := strconv.ParseFloat(s, 64)
  822. if err != nil {
  823. return playSeconds, err
  824. }
  825. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  826. }
  827. return
  828. }
  829. // GetTimeSubDay 计算两个时间的自然日期差(后面减去前面)
  830. func GetTimeSubDay(t1, t2 time.Time) int {
  831. var day int
  832. swap := false
  833. if t1.Unix() > t2.Unix() {
  834. t1, t2 = t2, t1
  835. swap = true
  836. }
  837. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  838. day = int(t2.Sub(t1).Hours() / 24)
  839. // 计算在t1+两个时间的余数之后天数是否有变化
  840. if t1_.Day() != t1.Day() {
  841. day += 1
  842. }
  843. if swap {
  844. day = -day
  845. }
  846. return day
  847. }
  848. // HmacSha256 计算HmacSha256
  849. // key 是加密所使用的key
  850. // data 是加密的内容
  851. func HmacSha256(key string, data string) []byte {
  852. mac := hmac.New(sha256.New, []byte(key))
  853. _, _ = mac.Write([]byte(data))
  854. return mac.Sum(nil)
  855. }
  856. // HmacSha256ToBase64 将加密后的二进制转Base64字符串
  857. func HmacSha256ToBase64(key string, data string) string {
  858. return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
  859. }