common.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "github.com/PuerkitoBio/goquery"
  10. "html"
  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. "unicode"
  23. "unicode/utf8"
  24. )
  25. // 随机数种子
  26. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  27. func GetRandString(size int) string {
  28. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  29. randomSb := ""
  30. digitSize := len(allLetterDigit)
  31. for i := 0; i < size; i++ {
  32. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  33. }
  34. return randomSb
  35. }
  36. func GetRandStringNoSpecialChar(size int) string {
  37. 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"}
  38. randomSb := ""
  39. digitSize := len(allLetterDigit)
  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. // 获取数字随机字符
  69. func GetRandDigit(n int) string {
  70. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  71. }
  72. // 获取随机数
  73. func GetRandNumber(n int) int {
  74. return rnd.Intn(n)
  75. }
  76. func GetRandInt(min, max int) int {
  77. if min >= max || min == 0 || max == 0 {
  78. return max
  79. }
  80. return rand.Intn(max-min) + min
  81. }
  82. func GetToday(format string) string {
  83. today := time.Now().Format(format)
  84. return today
  85. }
  86. // 获取今天剩余秒数
  87. func GetTodayLastSecond() time.Duration {
  88. today := GetToday(FormatDate) + " 23:59:59"
  89. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  90. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  91. }
  92. // 处理出生日期函数
  93. func GetBrithDate(idcard string) string {
  94. l := len(idcard)
  95. var s string
  96. if l == 15 {
  97. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  98. return s
  99. }
  100. if l == 18 {
  101. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  102. return s
  103. }
  104. return GetToday(FormatDate)
  105. }
  106. // 处理性别
  107. func WhichSexByIdcard(idcard string) string {
  108. var sexs = [2]string{"女", "男"}
  109. length := len(idcard)
  110. if length == 18 {
  111. sex, _ := strconv.Atoi(string(idcard[16]))
  112. return sexs[sex%2]
  113. } else if length == 15 {
  114. sex, _ := strconv.Atoi(string(idcard[14]))
  115. return sexs[sex%2]
  116. }
  117. return "男"
  118. }
  119. // 截取小数点后几位
  120. func SubFloatToString(f float64, m int) string {
  121. n := strconv.FormatFloat(f, 'f', -1, 64)
  122. if n == "" {
  123. return ""
  124. }
  125. if m >= len(n) {
  126. return n
  127. }
  128. newn := strings.Split(n, ".")
  129. if m == 0 {
  130. return newn[0]
  131. }
  132. if len(newn) < 2 || m >= len(newn[1]) {
  133. return n
  134. }
  135. return newn[0] + "." + newn[1][:m]
  136. }
  137. // 截取小数点后几位
  138. func SubFloatToFloat(f float64, m int) float64 {
  139. newn := SubFloatToString(f, m)
  140. newf, _ := strconv.ParseFloat(newn, 64)
  141. return newf
  142. }
  143. // 获取相差时间-年
  144. func GetYearDiffer(start_time, end_time string) int {
  145. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  146. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  147. age := t2.Year() - t1.Year()
  148. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  149. age--
  150. }
  151. return age
  152. }
  153. // 获取相差时间-秒
  154. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  155. diff := end_time.Unix() - start_time.Unix()
  156. return diff
  157. }
  158. func FixFloat(f float64, m int) float64 {
  159. newn := SubFloatToString(f+0.00000001, m)
  160. newf, _ := strconv.ParseFloat(newn, 64)
  161. return newf
  162. }
  163. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  164. func StrListToString(strList []string) (str string) {
  165. if len(strList) > 0 {
  166. for k, v := range strList {
  167. if k == 0 {
  168. str = v
  169. } else {
  170. str = str + "," + v
  171. }
  172. }
  173. return
  174. }
  175. return ""
  176. }
  177. // Token
  178. func GetToken() string {
  179. randStr := GetRandString(64)
  180. token := MD5(randStr + Md5Key)
  181. tokenLen := 64 - len(token)
  182. return strings.ToUpper(token + GetRandString(tokenLen))
  183. }
  184. // 数据没有记录
  185. func ErrNoRow() string {
  186. return "<QuerySeter> no row found"
  187. }
  188. // 校验邮箱格式
  189. func ValidateEmailFormatat(email string) bool {
  190. reg := regexp.MustCompile(RegularEmail)
  191. return reg.MatchString(email)
  192. }
  193. // 验证是否是手机号
  194. func ValidateMobileFormatat(mobileNum string) bool {
  195. reg := regexp.MustCompile(RegularMobile)
  196. return reg.MatchString(mobileNum)
  197. }
  198. // 验证是否是固定电话
  199. func ValidateFixedTelephoneFormatat(mobileNum string) bool {
  200. reg := regexp.MustCompile(RegularFixedTelephone)
  201. return reg.MatchString(mobileNum)
  202. }
  203. // 判断文件是否存在
  204. func FileIsExist(filePath string) bool {
  205. _, err := os.Stat(filePath)
  206. return err == nil || os.IsExist(err)
  207. }
  208. // 获取图片扩展名
  209. func GetImgExt(file string) (ext string, err error) {
  210. var headerByte []byte
  211. headerByte = make([]byte, 8)
  212. fd, err := os.Open(file)
  213. if err != nil {
  214. return "", err
  215. }
  216. defer fd.Close()
  217. _, err = fd.Read(headerByte)
  218. if err != nil {
  219. return "", err
  220. }
  221. xStr := fmt.Sprintf("%x", headerByte)
  222. switch {
  223. case xStr == "89504e470d0a1a0a":
  224. ext = ".png"
  225. case xStr == "0000010001002020":
  226. ext = ".ico"
  227. case xStr == "0000020001002020":
  228. ext = ".cur"
  229. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  230. ext = ".gif"
  231. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  232. ext = ".tga"
  233. case xStr[:8] == "464f524d":
  234. ext = ".iff"
  235. case xStr[:8] == "52494646":
  236. ext = ".ani"
  237. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  238. ext = ".tiff"
  239. case xStr[:4] == "424d":
  240. ext = ".bmp"
  241. case xStr[:4] == "ffd8":
  242. ext = ".jpg"
  243. case xStr[:2] == "0a":
  244. ext = ".pcx"
  245. default:
  246. ext = ""
  247. }
  248. return ext, nil
  249. }
  250. // 保存图片
  251. func SaveImage(path string, img image.Image) (err error) {
  252. //需要保持的文件
  253. imgfile, err := os.Create(path)
  254. defer imgfile.Close()
  255. // 以PNG格式保存文件
  256. err = png.Encode(imgfile, img)
  257. return err
  258. }
  259. // 保存base64数据为文件
  260. func SaveBase64ToFile(content, path string) error {
  261. data, err := base64.StdEncoding.DecodeString(content)
  262. if err != nil {
  263. return err
  264. }
  265. f, err := os.Create(path)
  266. defer f.Close()
  267. if err != nil {
  268. return err
  269. }
  270. f.Write(data)
  271. return nil
  272. }
  273. func SaveBase64ToFileBySeek(content, path string) (err error) {
  274. data, err := base64.StdEncoding.DecodeString(content)
  275. exist, err := PathExists(path)
  276. if err != nil {
  277. return
  278. }
  279. if !exist {
  280. f, err := os.Create(path)
  281. if err != nil {
  282. return err
  283. }
  284. n, _ := f.Seek(0, 2)
  285. // 从末尾的偏移量开始写入内容
  286. _, err = f.WriteAt([]byte(data), n)
  287. defer f.Close()
  288. } else {
  289. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  290. if err != nil {
  291. return err
  292. }
  293. n, _ := f.Seek(0, 2)
  294. // 从末尾的偏移量开始写入内容
  295. _, err = f.WriteAt([]byte(data), n)
  296. defer f.Close()
  297. }
  298. return nil
  299. }
  300. func PathExists(path string) (bool, error) {
  301. _, err := os.Stat(path)
  302. if err == nil {
  303. return true, nil
  304. }
  305. if os.IsNotExist(err) {
  306. return false, nil
  307. }
  308. return false, err
  309. }
  310. func StartIndex(page, pagesize int) int {
  311. if page > 1 {
  312. return (page - 1) * pagesize
  313. }
  314. return 0
  315. }
  316. func PageCount(count, pagesize int) int {
  317. if count%pagesize > 0 {
  318. return count/pagesize + 1
  319. } else {
  320. return count / pagesize
  321. }
  322. }
  323. func TrimHtml(src string) string {
  324. //将HTML标签全转换成小写
  325. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  326. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  327. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  328. src = re.ReplaceAllString(src, "[图片]")
  329. re, _ = regexp.Compile("class[\\S\\s]+?>")
  330. src = re.ReplaceAllString(src, "")
  331. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  332. src = re.ReplaceAllString(src, "")
  333. return strings.TrimSpace(src)
  334. }
  335. //1556164246 -> 2019-04-25 03:50:46 +0000
  336. //timestamp
  337. func TimeToTimestamp() {
  338. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  339. }
  340. func ToUnicode(text string) string {
  341. textQuoted := strconv.QuoteToASCII(text)
  342. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  343. return textUnquoted
  344. }
  345. func VersionToInt(version string) int {
  346. version = strings.Replace(version, ".", "", -1)
  347. n, _ := strconv.Atoi(version)
  348. return n
  349. }
  350. func IsCheckInList(list []int, s int) bool {
  351. for _, v := range list {
  352. if v == s {
  353. return true
  354. }
  355. }
  356. return false
  357. }
  358. func round(num float64) int {
  359. return int(num + math.Copysign(0.5, num))
  360. }
  361. func toFixed(num float64, precision int) float64 {
  362. output := math.Pow(10, float64(precision))
  363. return float64(round(num*output)) / output
  364. }
  365. // GetWilsonScore returns Wilson Score
  366. func GetWilsonScore(p, n float64) float64 {
  367. if p == 0 && n == 0 {
  368. return 0
  369. }
  370. 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)
  371. }
  372. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  373. func ChangeWordsToNum(str string) (numStr string) {
  374. words := ([]rune)(str)
  375. num := 0
  376. n := 0
  377. for i := 0; i < len(words); i++ {
  378. word := string(words[i : i+1])
  379. switch word {
  380. case "万":
  381. if n == 0 {
  382. n = 1
  383. }
  384. n = n * 10000
  385. num = num*10000 + n
  386. n = 0
  387. case "千":
  388. if n == 0 {
  389. n = 1
  390. }
  391. n = n * 1000
  392. num += n
  393. n = 0
  394. case "百":
  395. if n == 0 {
  396. n = 1
  397. }
  398. n = n * 100
  399. num += n
  400. n = 0
  401. case "十":
  402. if n == 0 {
  403. n = 1
  404. }
  405. n = n * 10
  406. num += n
  407. n = 0
  408. case "一":
  409. n += 1
  410. case "二":
  411. n += 2
  412. case "三":
  413. n += 3
  414. case "四":
  415. n += 4
  416. case "五":
  417. n += 5
  418. case "六":
  419. n += 6
  420. case "七":
  421. n += 7
  422. case "八":
  423. n += 8
  424. case "九":
  425. n += 9
  426. case "零":
  427. default:
  428. if n > 0 {
  429. num += n
  430. n = 0
  431. }
  432. if num == 0 {
  433. numStr += word
  434. } else {
  435. numStr += strconv.Itoa(num) + word
  436. num = 0
  437. }
  438. }
  439. }
  440. if n > 0 {
  441. num += n
  442. n = 0
  443. }
  444. if num != 0 {
  445. numStr += strconv.Itoa(num)
  446. }
  447. return
  448. }
  449. func Sha1(data string) string {
  450. sha1 := sha1.New()
  451. sha1.Write([]byte(data))
  452. return hex.EncodeToString(sha1.Sum([]byte("")))
  453. }
  454. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  455. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  456. out, err := exec.Command("bash", "-c", cmd).Output()
  457. if err != nil {
  458. return
  459. }
  460. outTimes := string(out)
  461. fmt.Println("outTimes:", outTimes)
  462. if outTimes != "" {
  463. timeArr := strings.Split(outTimes, ":")
  464. h := timeArr[0]
  465. m := timeArr[1]
  466. s := timeArr[2]
  467. hInt, err := strconv.Atoi(h)
  468. if err != nil {
  469. return playSeconds, err
  470. }
  471. mInt, err := strconv.Atoi(m)
  472. if err != nil {
  473. return playSeconds, err
  474. }
  475. s = strings.Trim(s, " ")
  476. s = strings.Trim(s, "\n")
  477. sInt, err := strconv.ParseFloat(s, 64)
  478. if err != nil {
  479. return playSeconds, err
  480. }
  481. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  482. }
  483. return
  484. }
  485. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  486. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  487. tradeCode = strings.Trim(tradeCode, " ")
  488. tradeCodeInt, err := strconv.Atoi(tradeCode)
  489. if err != nil {
  490. return
  491. }
  492. tradeCodeInt = tradeCodeInt + 1
  493. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  494. return
  495. }
  496. // excel日期字段格式化 yyyy-mm-dd
  497. func ConvertToFormatDay(excelDaysString string) string {
  498. // 2006-01-02 距离 1900-01-01的天数
  499. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  500. curDiffDay := excelDaysString
  501. b, _ := strconv.Atoi(curDiffDay)
  502. // 获取excel的日期距离2006-01-02的天数
  503. realDiffDay := b - baseDiffDay
  504. //fmt.Println("realDiffDay:",realDiffDay)
  505. // 距离2006-01-02 秒数
  506. realDiffSecond := realDiffDay * 24 * 3600
  507. //fmt.Println("realDiffSecond:",realDiffSecond)
  508. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  509. baseOriginSecond := 1136185445
  510. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  511. return resultTime
  512. }
  513. // 字符串转换为time
  514. func StrTimeToTime(strTime string) time.Time {
  515. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  516. loc, _ := time.LoadLocation("Local") //重要:获取时区
  517. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  518. return resultTime
  519. }
  520. // 时间格式去掉时分秒
  521. func TimeRemoveHms(strTime string) string {
  522. var Ymd string
  523. var resultTime = StrTimeToTime(strTime)
  524. year := resultTime.Year()
  525. month := resultTime.Format("01")
  526. day1 := resultTime.Day()
  527. if day1 < 10 {
  528. Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
  529. } else {
  530. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  531. }
  532. return Ymd
  533. }
  534. // 判断时间是当年的第几周
  535. func WeekByDate(t time.Time) string {
  536. var resultSAtr string
  537. t = t.AddDate(0, 0, -8) // 减少八天跟老数据标题统一
  538. yearDay := t.YearDay()
  539. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  540. firstDayInWeek := int(yearFirstDay.Weekday())
  541. //今年第一周有几天
  542. firstWeekDays := 1
  543. if firstDayInWeek != 0 {
  544. firstWeekDays = 7 - firstDayInWeek + 1
  545. }
  546. var week int
  547. if yearDay <= firstWeekDays {
  548. week = 1
  549. } else {
  550. week = (yearDay-firstWeekDays)/7 + 2
  551. }
  552. resultSAtr = "(" + strconv.Itoa(t.Year()) + "年第" + strconv.Itoa(week) + "周" + ")"
  553. return resultSAtr
  554. }
  555. func Mp3Time(videoPlaySeconds string) string {
  556. var d int
  557. var timeStr string
  558. a, _ := strconv.ParseFloat(videoPlaySeconds, 32)
  559. b := int(a)
  560. c := b % 60
  561. d = b / 60
  562. if b <= 60 {
  563. timeStr = "00:" + strconv.Itoa(b)
  564. } else {
  565. if d < 10 {
  566. timeStr = "0" + strconv.Itoa(d) + ":" + strconv.Itoa(c)
  567. } else {
  568. timeStr = strconv.Itoa(d) + ":" + strconv.Itoa(c)
  569. }
  570. }
  571. return timeStr
  572. }
  573. func GetLocalIP() (ip string, err error) {
  574. addrs, err := net.InterfaceAddrs()
  575. if err != nil {
  576. return
  577. }
  578. for _, addr := range addrs {
  579. ipAddr, ok := addr.(*net.IPNet)
  580. if !ok {
  581. continue
  582. }
  583. if ipAddr.IP.IsLoopback() {
  584. continue
  585. }
  586. if !ipAddr.IP.IsGlobalUnicast() {
  587. continue
  588. }
  589. return ipAddr.IP.String(), nil
  590. }
  591. return
  592. }
  593. // GetOrmInReplace 获取orm的in查询替换?的方法
  594. func GetOrmInReplace(num int) string {
  595. template := make([]string, num)
  596. for i := 0; i < num; i++ {
  597. template[i] = "?"
  598. }
  599. return strings.Join(template, ",")
  600. }
  601. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  602. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  603. for _, id := range idStrList {
  604. if id == searchId {
  605. has = true
  606. return
  607. }
  608. }
  609. return
  610. }
  611. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  612. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  613. for _, id := range idIntList {
  614. if id == searchId {
  615. has = true
  616. return
  617. }
  618. }
  619. return
  620. }
  621. // GetNowWeekMonday 获取本周周一的时间
  622. func GetNowWeekMonday() time.Time {
  623. offset := int(time.Monday - time.Now().Weekday())
  624. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  625. offset = -6
  626. }
  627. mondayTime := time.Now().AddDate(0, 0, offset)
  628. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  629. return mondayTime
  630. }
  631. // GetLastWeekMonday 获取上周周一的时间
  632. func GetLastWeekMonday() time.Time {
  633. offset := int(time.Monday - time.Now().Weekday())
  634. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  635. offset = -6
  636. }
  637. mondayTime := time.Now().AddDate(0, 0, offset-7)
  638. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  639. return mondayTime
  640. }
  641. // GetNowWeekSunDay 获取本周周日的时间
  642. func GetNowWeekSunday() time.Time {
  643. return GetNowWeekMonday().AddDate(0, 0, 6)
  644. }
  645. // GetLastWeekSunday 获取上周周日的时间
  646. func GetLastWeekSunday() time.Time {
  647. return GetLastWeekMonday().AddDate(0, 0, 6)
  648. }
  649. // GetNowMonthFirstDay 获取本月第一天的时间
  650. func GetNowMonthFirstDay() time.Time {
  651. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  652. return nowMonthFirstDay
  653. }
  654. // GetNowMonthLastDay 获取本月最后一天的时间
  655. func GetNowMonthLastDay() time.Time {
  656. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  657. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  658. return nowMonthLastDay
  659. }
  660. // GetNowMonthFirstDay 获取上月第一天的时间
  661. func GetLastMonthFirstDay() time.Time {
  662. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().AddDate(0, -1, 0).Month(), 1, 0, 0, 0, 0, time.Now().Location())
  663. return nowMonthFirstDay
  664. }
  665. // GetNowMonthLastDay 获取上月最后一天的时间
  666. func GetLastMonthLastDay() time.Time {
  667. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().AddDate(0, -1, 0).Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  668. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  669. return nowMonthLastDay
  670. }
  671. // 时间格式去掉时分秒
  672. func TimeRemoveHms2(strTime string) string {
  673. var Ymd string
  674. var resultTime = StrTimeToTime(strTime)
  675. year := resultTime.Year()
  676. month := resultTime.Format("01")
  677. day1 := resultTime.Day()
  678. if day1 < 10 {
  679. Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
  680. } else {
  681. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  682. }
  683. return Ymd
  684. }
  685. // 时间格式去掉年
  686. func GetTimeDateRemoveYear(strTime string) (dataStr string) {
  687. slicePublishTime := strings.Split(strTime, "-")
  688. for k, v := range slicePublishTime {
  689. if k == 0 {
  690. continue
  691. }
  692. dataStr += v + "-"
  693. }
  694. dataStr = strings.TrimRight(dataStr, "-")
  695. return dataStr
  696. }
  697. // 时间格式去掉年和秒
  698. func GetTimeDateRemoveYearAndSecond(strTime string) (dataStr string) {
  699. slicePublishTime := strings.Split(strTime, "-")
  700. for k, v := range slicePublishTime {
  701. if k == 0 {
  702. continue
  703. }
  704. dataStr += v + "-"
  705. }
  706. dataStr = strings.TrimRight(dataStr, "-")
  707. dataStr = dataStr[:len(dataStr)-3]
  708. return
  709. }
  710. func ArticleHasImgUrl(body string) (hasImg bool, err error) {
  711. r := strings.NewReader(string(body))
  712. doc, err := goquery.NewDocumentFromReader(r)
  713. if err != nil {
  714. fmt.Println(err)
  715. }
  716. doc.Find("img").Each(func(i int, s *goquery.Selection) {
  717. hasImg = true
  718. })
  719. return
  720. }
  721. func ArticleRemoveImgUrl(body string) (result string) {
  722. // 使用正则表达式去除img标签
  723. re := regexp.MustCompile(`<img[^>]*>`)
  724. result = re.ReplaceAllString(body, "")
  725. return
  726. }
  727. func FindArticleImgUrls(body string) (imgUrls []string, err error) {
  728. r := strings.NewReader(string(body))
  729. doc, err := goquery.NewDocumentFromReader(r)
  730. if err != nil {
  731. fmt.Println(err)
  732. }
  733. doc.Find("img").Each(func(i int, s *goquery.Selection) {
  734. src, _ := s.Attr("src")
  735. imgUrls = append(imgUrls, src)
  736. })
  737. return
  738. }
  739. // 去除部分style
  740. func ExtractText(body string) (result string, err error) {
  741. // 使用正则表达式去除img标签
  742. re := regexp.MustCompile(`<section style[\s\S]*?>`)
  743. result = re.ReplaceAllString(body, "")
  744. re = regexp.MustCompile(`<span style[\s\S]*?>`)
  745. result = re.ReplaceAllString(result, "")
  746. return
  747. }
  748. // 富文本字符串截取指定长度
  749. func InterceptHtmlLength(body string, length int) (newbody string) {
  750. content := html.UnescapeString(body)
  751. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  752. if err != nil {
  753. fmt.Println("create doc err:", err.Error())
  754. return
  755. }
  756. bodyText := doc.Text()
  757. if len(bodyText) < length {
  758. length = len(bodyText)
  759. }
  760. newbody = bodyText[0:length]
  761. return
  762. }
  763. // 字符串转换为time类型
  764. func StrDateToDate(strTime string) time.Time {
  765. timeLayout := "2006-01-02" //转化所需模板
  766. loc, _ := time.LoadLocation("Local") //重要:获取时区
  767. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  768. return resultTime
  769. }
  770. // 处理活动名称
  771. func TruncateActivityNameString(s string) string {
  772. // 计算字符串总字数(按汉字、数字、字母和特殊符号计算)
  773. totalCharCount := utf8.RuneCountInString(s)
  774. // 如果总字数不超过18,则直接返回整个字符串
  775. if totalCharCount <= 18 {
  776. return s
  777. }
  778. // 计算前15个汉字所需的字节位置
  779. hanziCount := 0
  780. byteIndex := 0
  781. for byteIndex < len(s) && hanziCount < 15 {
  782. r, size := utf8.DecodeRuneInString(s[byteIndex:])
  783. if r != utf8.RuneError {
  784. hanziCount++
  785. }
  786. byteIndex += size
  787. }
  788. // 截取前15个汉字,并添加省略号
  789. return s[:byteIndex] + "…"
  790. }
  791. func GetOrdernum() string {
  792. now := time.Now().UnixNano()
  793. // 生成4位随机数
  794. rand.Seed(now)
  795. randomPart := rand.Intn(10000)
  796. // 拼接订单号
  797. orderSn := "OD" + time.Now().Format(FormatDateTimeUnSpace) + fmt.Sprintf("%04d", randomPart)
  798. return orderSn
  799. }
  800. // 获取字符串中的阿拉伯数字,并返回字符串
  801. func GetArabicNumbers(str string) string {
  802. var numbers []rune
  803. for _, char := range str {
  804. if unicode.IsDigit(char) {
  805. numbers = append(numbers, char)
  806. }
  807. }
  808. return string(numbers)
  809. }