common.go 24 KB

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