common.go 22 KB

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