common.go 24 KB

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