common.go 24 KB

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