common.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/sha1"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "github.com/astaxie/beego/logs"
  10. "github.com/dgrijalva/jwt-go"
  11. "gorm.io/gorm"
  12. "math"
  13. "math/rand"
  14. "os/exec"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "time"
  19. )
  20. var ErrNoRow = gorm.ErrRecordNotFound
  21. var (
  22. KEY = []byte("5Mb5Gdmb5y")
  23. )
  24. // GenToken 发放token
  25. func GenToken(account string) string {
  26. token := jwt.New(jwt.SigningMethodHS256)
  27. token.Claims = &jwt.StandardClaims{
  28. NotBefore: int64(time.Now().Unix()),
  29. ExpiresAt: int64(time.Now().Unix() + 90*24*60*60),
  30. Issuer: "hongze_admin",
  31. Subject: account,
  32. }
  33. ss, err := token.SignedString(KEY)
  34. if err != nil {
  35. logs.Error(err)
  36. return ""
  37. }
  38. return ss
  39. }
  40. // 随机数种子
  41. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  42. // GetRandString 获取随机字符串
  43. func GetRandString(size int) string {
  44. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  45. randomSb := ""
  46. digitSize := len(allLetterDigit)
  47. for i := 0; i < size; i++ {
  48. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  49. }
  50. return randomSb
  51. }
  52. // GetRandStringNoSpecialChar
  53. func GetRandStringNoSpecialChar(size int) string {
  54. 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"}
  55. randomSb := ""
  56. digitSize := len(allLetterDigit)
  57. for i := 0; i < size; i++ {
  58. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  59. }
  60. return randomSb
  61. }
  62. // StringsToJSON
  63. func StringsToJSON(str string) string {
  64. rs := []rune(str)
  65. jsons := ""
  66. for _, r := range rs {
  67. rint := int(r)
  68. if rint < 128 {
  69. jsons += string(r)
  70. } else {
  71. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  72. }
  73. }
  74. return jsons
  75. }
  76. // ToString 序列化
  77. func ToString(v interface{}) string {
  78. data, _ := json.Marshal(v)
  79. return string(data)
  80. }
  81. // MD5 md5加密
  82. func MD5(data string) string {
  83. m := md5.Sum([]byte(data))
  84. return hex.EncodeToString(m[:])
  85. }
  86. // GetRandDigit 获取数字随机字符
  87. func GetRandDigit(n int) string {
  88. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  89. }
  90. // GetRandNumber 获取随机数
  91. func GetRandNumber(n int) int {
  92. return rnd.Intn(n)
  93. }
  94. // GetRandInt
  95. func GetRandInt(min, max int) int {
  96. if min >= max || min == 0 || max == 0 {
  97. return max
  98. }
  99. return rand.Intn(max-min) + min
  100. }
  101. // GetToday 获取今天的随机字符
  102. func GetToday(format string) string {
  103. today := time.Now().Format(format)
  104. return today
  105. }
  106. // GetTodayLastSecond 获取今天剩余秒数
  107. func GetTodayLastSecond() time.Duration {
  108. today := GetToday(FormatDate) + " 23:59:59"
  109. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  110. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  111. }
  112. // GetBrithDate 处理出生日期函数
  113. func GetBrithDate(idcard string) string {
  114. l := len(idcard)
  115. var s string
  116. if l == 15 {
  117. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  118. return s
  119. }
  120. if l == 18 {
  121. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  122. return s
  123. }
  124. return GetToday(FormatDate)
  125. }
  126. // WhichSexByIdcard 处理性别
  127. func WhichSexByIdcard(idcard string) string {
  128. var sexs = [2]string{"女", "男"}
  129. length := len(idcard)
  130. if length == 18 {
  131. sex, _ := strconv.Atoi(string(idcard[16]))
  132. return sexs[sex%2]
  133. } else if length == 15 {
  134. sex, _ := strconv.Atoi(string(idcard[14]))
  135. return sexs[sex%2]
  136. }
  137. return "男"
  138. }
  139. // SubFloatToString 截取小数点后几位
  140. func SubFloatToString(f float64, m int) string {
  141. n := strconv.FormatFloat(f, 'f', -1, 64)
  142. if n == "" {
  143. return ""
  144. }
  145. if m >= len(n) {
  146. return n
  147. }
  148. newn := strings.Split(n, ".")
  149. if m == 0 {
  150. return newn[0]
  151. }
  152. if len(newn) < 2 || m >= len(newn[1]) {
  153. return n
  154. }
  155. return newn[0] + "." + newn[1][:m]
  156. }
  157. // SubFloatToFloat 截取小数点后几位
  158. func SubFloatToFloat(f float64, m int) float64 {
  159. newn := SubFloatToString(f, m)
  160. newf, _ := strconv.ParseFloat(newn, 64)
  161. return newf
  162. }
  163. // SubFloatToFloatStr 截取小数点后几位
  164. func SubFloatToFloatStr(f float64, m int) string {
  165. newn := SubFloatToString(f, m)
  166. return newn
  167. }
  168. // GetYearDiffer 获取相差时间-年
  169. func GetYearDiffer(start_time, end_time string) int {
  170. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  171. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  172. age := t2.Year() - t1.Year()
  173. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  174. age--
  175. }
  176. return age
  177. }
  178. // GetSecondDifferByTime 获取相差时间-秒
  179. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  180. diff := end_time.Unix() - start_time.Unix()
  181. return diff
  182. }
  183. // FixFloat
  184. func FixFloat(f float64, m int) float64 {
  185. newn := SubFloatToString(f+0.00000001, m)
  186. newf, _ := strconv.ParseFloat(newn, 64)
  187. return newf
  188. }
  189. // StrListToString 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  190. func StrListToString(strList []string) (str string) {
  191. if len(strList) > 0 {
  192. for k, v := range strList {
  193. if k == 0 {
  194. str = v
  195. } else {
  196. str = str + "," + v
  197. }
  198. }
  199. return
  200. }
  201. return ""
  202. }
  203. // ValidateEmailFormatat 校验邮箱格式
  204. func ValidateEmailFormatat(email string) bool {
  205. reg := regexp.MustCompile(RegularEmail)
  206. return reg.MatchString(email)
  207. }
  208. // ValidateMobileFormatat 验证是否是手机号
  209. func ValidateMobileFormatat(mobileNum string) bool {
  210. reg := regexp.MustCompile(RegularMobile)
  211. return reg.MatchString(mobileNum)
  212. }
  213. // StartIndex 开始下标
  214. func StartIndex(page, pagesize int) int {
  215. if page > 1 {
  216. return (page - 1) * pagesize
  217. }
  218. return 0
  219. }
  220. // PageCount
  221. func PageCount(count, pagesize int) int {
  222. if count%pagesize > 0 {
  223. return count/pagesize + 1
  224. } else {
  225. return count / pagesize
  226. }
  227. }
  228. // TrimHtml
  229. func TrimHtml(src string) string {
  230. //将HTML标签全转换成小写
  231. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  232. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  233. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  234. src = re.ReplaceAllString(src, "")
  235. re, _ = regexp.Compile("class[\\S\\s]+?>")
  236. src = re.ReplaceAllString(src, "")
  237. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  238. src = re.ReplaceAllString(src, "")
  239. return strings.TrimSpace(src)
  240. }
  241. // 1556164246 -> 2019-04-25 03:50:46 +0000
  242. // timestamp
  243. // TimeToTimestamp
  244. func TimeToTimestamp() {
  245. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  246. }
  247. func TimeTransferString(format string, t time.Time) string {
  248. str := t.Format(format)
  249. var emptyT time.Time
  250. if str == emptyT.Format(format) {
  251. return ""
  252. }
  253. return str
  254. }
  255. // ToUnicode
  256. func ToUnicode(text string) string {
  257. textQuoted := strconv.QuoteToASCII(text)
  258. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  259. return textUnquoted
  260. }
  261. // VersionToInt
  262. func VersionToInt(version string) int {
  263. version = strings.Replace(version, ".", "", -1)
  264. n, _ := strconv.Atoi(version)
  265. return n
  266. }
  267. // IsCheckInList
  268. func IsCheckInList(list []int, s int) bool {
  269. for _, v := range list {
  270. if v == s {
  271. return true
  272. }
  273. }
  274. return false
  275. }
  276. // round
  277. func round(num float64) int {
  278. return int(num + math.Copysign(0.5, num))
  279. }
  280. // toFixed
  281. func toFixed(num float64, precision int) float64 {
  282. output := math.Pow(10, float64(precision))
  283. return float64(round(num*output)) / output
  284. }
  285. // GetWilsonScore returns Wilson Score
  286. func GetWilsonScore(p, n float64) float64 {
  287. if p == 0 && n == 0 {
  288. return 0
  289. }
  290. 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)
  291. }
  292. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  293. func ChangeWordsToNum(str string) (numStr string) {
  294. words := ([]rune)(str)
  295. num := 0
  296. n := 0
  297. for i := 0; i < len(words); i++ {
  298. word := string(words[i : i+1])
  299. switch word {
  300. case "万":
  301. if n == 0 {
  302. n = 1
  303. }
  304. n = n * 10000
  305. num = num*10000 + n
  306. n = 0
  307. case "千":
  308. if n == 0 {
  309. n = 1
  310. }
  311. n = n * 1000
  312. num += n
  313. n = 0
  314. case "百":
  315. if n == 0 {
  316. n = 1
  317. }
  318. n = n * 100
  319. num += n
  320. n = 0
  321. case "十":
  322. if n == 0 {
  323. n = 1
  324. }
  325. n = n * 10
  326. num += n
  327. n = 0
  328. case "一":
  329. n += 1
  330. case "二":
  331. n += 2
  332. case "三":
  333. n += 3
  334. case "四":
  335. n += 4
  336. case "五":
  337. n += 5
  338. case "六":
  339. n += 6
  340. case "七":
  341. n += 7
  342. case "八":
  343. n += 8
  344. case "九":
  345. n += 9
  346. case "零":
  347. default:
  348. if n > 0 {
  349. num += n
  350. n = 0
  351. }
  352. if num == 0 {
  353. numStr += word
  354. } else {
  355. numStr += strconv.Itoa(num) + word
  356. num = 0
  357. }
  358. }
  359. }
  360. if n > 0 {
  361. num += n
  362. n = 0
  363. }
  364. if num != 0 {
  365. numStr += strconv.Itoa(num)
  366. }
  367. return
  368. }
  369. // Sha1
  370. func Sha1(data string) string {
  371. sha1 := sha1.New()
  372. sha1.Write([]byte(data))
  373. return hex.EncodeToString(sha1.Sum([]byte("")))
  374. }
  375. // GetVideoPlaySeconds
  376. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  377. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  378. out, err := exec.Command("bash", "-c", cmd).Output()
  379. if err != nil {
  380. return
  381. }
  382. outTimes := string(out)
  383. fmt.Println("outTimes:", outTimes)
  384. if outTimes != "" {
  385. timeArr := strings.Split(outTimes, ":")
  386. h := timeArr[0]
  387. m := timeArr[1]
  388. s := timeArr[2]
  389. hInt, err := strconv.Atoi(h)
  390. if err != nil {
  391. return playSeconds, err
  392. }
  393. mInt, err := strconv.Atoi(m)
  394. if err != nil {
  395. return playSeconds, err
  396. }
  397. s = strings.Trim(s, " ")
  398. s = strings.Trim(s, "\n")
  399. sInt, err := strconv.ParseFloat(s, 64)
  400. if err != nil {
  401. return playSeconds, err
  402. }
  403. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  404. }
  405. return
  406. }
  407. // GetMaxTradeCode
  408. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  409. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  410. tradeCode = strings.Trim(tradeCode, " ")
  411. tradeCodeInt, err := strconv.Atoi(tradeCode)
  412. if err != nil {
  413. return
  414. }
  415. tradeCodeInt = tradeCodeInt + 1
  416. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  417. return
  418. }
  419. // ConvertToFormatDay excel日期字段格式化 yyyy-mm-dd
  420. func ConvertToFormatDay(excelDaysString string) string {
  421. // 2006-01-02 距离 1900-01-01的天数
  422. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  423. curDiffDay := excelDaysString
  424. b, _ := strconv.Atoi(curDiffDay)
  425. // 获取excel的日期距离2006-01-02的天数
  426. realDiffDay := b - baseDiffDay
  427. //fmt.Println("realDiffDay:",realDiffDay)
  428. // 距离2006-01-02 秒数
  429. realDiffSecond := realDiffDay * 24 * 3600
  430. //fmt.Println("realDiffSecond:",realDiffSecond)
  431. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  432. baseOriginSecond := 1136185445
  433. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  434. return resultTime
  435. }
  436. // CheckPwd
  437. func CheckPwd(pwd string) bool {
  438. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  439. reg := regexp.MustCompile(compile)
  440. flag := reg.MatchString(pwd)
  441. return flag
  442. }
  443. // GetMonthStartAndEnd
  444. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  445. // 数字月份必须前置补零
  446. if len(myMonth) == 1 {
  447. myMonth = "0" + myMonth
  448. }
  449. yInt, _ := strconv.Atoi(myYear)
  450. timeLayout := "2006-01-02 15:04:05"
  451. loc, _ := time.LoadLocation("Local")
  452. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  453. newMonth := theTime.Month()
  454. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  455. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  456. return t1, t2
  457. }
  458. // TrimStr 移除字符串中的空格
  459. func TrimStr(str string) (str2 string) {
  460. return strings.Replace(str, " ", "", -1)
  461. }
  462. // StrTimeToTime 字符串转换为time
  463. func StrTimeToTime(strTime string) time.Time {
  464. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  465. loc, _ := time.LoadLocation("Local") //重要:获取时区
  466. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  467. return resultTime
  468. }
  469. // StrDateTimeToWeek 字符串类型时间转周几
  470. func StrDateTimeToWeek(strTime string) string {
  471. var WeekDayMap = map[string]string{
  472. "Monday": "周一",
  473. "Tuesday": "周二",
  474. "Wednesday": "周三",
  475. "Thursday": "周四",
  476. "Friday": "周五",
  477. "Saturday": "周六",
  478. "Sunday": "周日",
  479. }
  480. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  481. startday, _ := time.Parse("2006-01-02", ctime)
  482. staweek_int := startday.Weekday().String()
  483. return WeekDayMap[staweek_int]
  484. }
  485. // TimeToStrYmd 时间格式转年月日字符串
  486. func TimeToStrYmd(time2 time.Time) string {
  487. var Ymd string
  488. year := time2.Year()
  489. month := time2.Format("1")
  490. day1 := time.Now().Day()
  491. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  492. return Ymd
  493. }
  494. // TimeRemoveHms 时间格式去掉时分秒
  495. func TimeRemoveHms(strTime string) string {
  496. var Ymd string
  497. var resultTime = StrTimeToTime(strTime)
  498. year := resultTime.Year()
  499. month := resultTime.Format("01")
  500. day1 := resultTime.Day()
  501. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  502. return Ymd
  503. }
  504. // ArticleLastTime 文章上一次编辑时间
  505. func ArticleLastTime(strTime string) string {
  506. var newTime string
  507. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  508. diffTime := time.Now().Unix() - stamp.Unix()
  509. if diffTime <= 60 {
  510. newTime = "当前"
  511. } else if diffTime < 60*60 {
  512. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  513. } else if diffTime < 24*60*60 {
  514. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  515. } else if diffTime < 30*24*60*60 {
  516. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  517. } else if diffTime < 12*30*24*60*60 {
  518. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  519. } else {
  520. newTime = "1年前"
  521. }
  522. return newTime
  523. }
  524. // ConvertNumToCny 人民币小写转大写
  525. func ConvertNumToCny(num float64) (str string, err error) {
  526. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  527. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  528. // log.Println(sliceUnit[:len(sliceUnit)-2])
  529. s := sliceUnit[len(sliceUnit)-len(strNum):]
  530. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  531. for k, v := range strNum[:] {
  532. str = str + upperDigitUnit[string(v)] + s[k]
  533. }
  534. reg, err := regexp.Compile(`零角零分$`)
  535. str = reg.ReplaceAllString(str, "整")
  536. reg, err = regexp.Compile(`零角`)
  537. str = reg.ReplaceAllString(str, "零")
  538. reg, err = regexp.Compile(`零分$`)
  539. str = reg.ReplaceAllString(str, "整")
  540. reg, err = regexp.Compile(`零[仟佰拾]`)
  541. str = reg.ReplaceAllString(str, "零")
  542. reg, err = regexp.Compile(`零{2,}`)
  543. str = reg.ReplaceAllString(str, "零")
  544. reg, err = regexp.Compile(`零亿`)
  545. str = reg.ReplaceAllString(str, "亿")
  546. reg, err = regexp.Compile(`零万`)
  547. str = reg.ReplaceAllString(str, "万")
  548. reg, err = regexp.Compile(`零*元`)
  549. str = reg.ReplaceAllString(str, "元")
  550. reg, err = regexp.Compile(`亿零{0, 3}万`)
  551. str = reg.ReplaceAllString(str, "^元")
  552. reg, err = regexp.Compile(`零元`)
  553. str = reg.ReplaceAllString(str, "零")
  554. return
  555. }
  556. // GetNowWeekMonday 获取本周周一的时间
  557. func GetNowWeekMonday() time.Time {
  558. offset := int(time.Monday - time.Now().Weekday())
  559. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  560. offset = -6
  561. }
  562. mondayTime := time.Now().AddDate(0, 0, offset)
  563. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  564. return mondayTime
  565. }
  566. // GetNowWeekLastDay 获取本周最后一天的时间
  567. func GetNowWeekLastDay() time.Time {
  568. offset := int(time.Monday - time.Now().Weekday())
  569. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  570. offset = -6
  571. }
  572. firstDayTime := time.Now().AddDate(0, 0, offset)
  573. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  574. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  575. return lastDayTime
  576. }
  577. // GetNowMonthFirstDay 获取本月第一天的时间
  578. func GetNowMonthFirstDay() time.Time {
  579. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  580. return nowMonthFirstDay
  581. }
  582. // GetNowMonthLastDay 获取本月最后一天的时间
  583. func GetNowMonthLastDay() time.Time {
  584. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  585. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  586. return nowMonthLastDay
  587. }
  588. // GetNowQuarterFirstDay 获取本季度第一天的时间
  589. func GetNowQuarterFirstDay() time.Time {
  590. month := int(time.Now().Month())
  591. var nowQuarterFirstDay time.Time
  592. if month >= 1 && month <= 3 {
  593. //1月1号
  594. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  595. } else if month >= 4 && month <= 6 {
  596. //4月1号
  597. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  598. } else if month >= 7 && month <= 9 {
  599. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  600. } else {
  601. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  602. }
  603. return nowQuarterFirstDay
  604. }
  605. // GetNowQuarterLastDay 获取本季度最后一天的时间
  606. func GetNowQuarterLastDay() time.Time {
  607. month := int(time.Now().Month())
  608. var nowQuarterLastDay time.Time
  609. if month >= 1 && month <= 3 {
  610. //03-31 23:59:59
  611. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  612. } else if month >= 4 && month <= 6 {
  613. //06-30 23:59:59
  614. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  615. } else if month >= 7 && month <= 9 {
  616. //09-30 23:59:59
  617. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  618. } else {
  619. //12-31 23:59:59
  620. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  621. }
  622. return nowQuarterLastDay
  623. }
  624. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  625. func GetNowHalfYearFirstDay() time.Time {
  626. month := int(time.Now().Month())
  627. var nowHalfYearLastDay time.Time
  628. if month >= 1 && month <= 6 {
  629. //03-31 23:59:59
  630. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  631. } else {
  632. //12-31 23:59:59
  633. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  634. }
  635. return nowHalfYearLastDay
  636. }
  637. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  638. func GetNowHalfYearLastDay() time.Time {
  639. month := int(time.Now().Month())
  640. var nowHalfYearLastDay time.Time
  641. if month >= 1 && month <= 6 {
  642. //03-31 23:59:59
  643. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  644. } else {
  645. //12-31 23:59:59
  646. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  647. }
  648. return nowHalfYearLastDay
  649. }
  650. // GetNowYearFirstDay 获取当前年的最后一天的时间
  651. func GetNowYearFirstDay() time.Time {
  652. //12-31 23:59:59
  653. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  654. return nowYearFirstDay
  655. }
  656. // GetNowYearLastDay 获取当前年的最后一天的时间
  657. func GetNowYearLastDay() time.Time {
  658. //12-31 23:59:59
  659. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  660. return nowYearLastDay
  661. }
  662. // CalculationDate 计算两个日期之间相差n年m月y天
  663. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  664. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  665. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  666. numYear := endDate.Year() - startDate.Year()
  667. numMonth := int(endDate.Month()) - int(startDate.Month())
  668. numDay := 0
  669. //获取截止月的总天数
  670. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  671. //获取截止月的前一个月
  672. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  673. //获取截止日期的上一个月的总天数
  674. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  675. //获取开始日期的的月份总天数
  676. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  677. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  678. if endDate.Day() == endDateDays {
  679. numDay = startDateMonthDays - startDate.Day() + 1
  680. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  681. if numDay == startDateMonthDays {
  682. numMonth++
  683. numDay = 0
  684. //超过月份了,那么年份加1
  685. if numMonth == 12 {
  686. numYear++
  687. numMonth = 0
  688. }
  689. }
  690. } else {
  691. numDay = endDate.Day() - startDate.Day() + 1
  692. }
  693. //天数小于0,那么向月份借一位
  694. if numDay < 0 {
  695. //向上一个月借一个月的天数
  696. numDay += endDatePrevMonthDays
  697. //总月份减去一个月
  698. numMonth = numMonth - 1
  699. }
  700. //月份小于0,那么向年份借一位
  701. if numMonth < 0 {
  702. //向上一个年借12个月
  703. numMonth += 12
  704. //总年份减去一年
  705. numYear = numYear - 1
  706. }
  707. if numYear < 0 {
  708. err = errors.New("日期异常")
  709. return
  710. }
  711. if numYear > 0 {
  712. beetweenDay += fmt.Sprint(numYear, "年")
  713. }
  714. if numMonth > 0 {
  715. beetweenDay += fmt.Sprint(numMonth, "个月")
  716. }
  717. if numDay > 0 {
  718. beetweenDay += fmt.Sprint(numDay, "天")
  719. }
  720. return
  721. }
  722. // getMonthDay 获取某年某月有多少天
  723. func getMonthDay(year, month int) (days int) {
  724. if month != 2 {
  725. if month == 4 || month == 6 || month == 9 || month == 11 {
  726. days = 30
  727. } else {
  728. days = 31
  729. }
  730. } else {
  731. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  732. days = 29
  733. } else {
  734. days = 28
  735. }
  736. }
  737. return
  738. }
  739. // InArray 是否在切片(数组/map)中含有该值,目前只支持:string、int 、 int64,其他都是返回false
  740. func InArray(needle interface{}, hyStack interface{}) bool {
  741. switch key := needle.(type) {
  742. case string:
  743. for _, item := range hyStack.([]string) {
  744. if key == item {
  745. return true
  746. }
  747. }
  748. case int:
  749. for _, item := range hyStack.([]int) {
  750. if key == item {
  751. return true
  752. }
  753. }
  754. case int64:
  755. for _, item := range hyStack.([]int64) {
  756. if key == item {
  757. return true
  758. }
  759. }
  760. default:
  761. return false
  762. }
  763. return false
  764. }
  765. // bit转MB 保留小数
  766. func Bit2MB(bitSize int64, prec int) (size float64) {
  767. mb := float64(bitSize) / float64(1024*1024)
  768. size, _ = strconv.ParseFloat(strconv.FormatFloat(mb, 'f', prec, 64), 64)
  769. return
  770. }
  771. // SubStr 截取字符串(中文)
  772. func SubStr(str string, subLen int) string {
  773. strRune := []rune(str)
  774. bodyRuneLen := len(strRune)
  775. if bodyRuneLen > subLen {
  776. bodyRuneLen = subLen
  777. }
  778. str = string(strRune[:bodyRuneLen])
  779. return str
  780. }
  781. func GetUpdateWeekEn(updateWeek string) string {
  782. switch updateWeek {
  783. case "周一":
  784. updateWeek = "monday"
  785. case "周二":
  786. updateWeek = "tuesday"
  787. case "周三":
  788. updateWeek = "wednesday"
  789. case "周四":
  790. updateWeek = "thursday"
  791. case "周五":
  792. updateWeek = "friday"
  793. case "周六":
  794. updateWeek = "saturday"
  795. case "周日":
  796. updateWeek = "sunday"
  797. }
  798. return updateWeek
  799. }
  800. func GetWeekZn(updateWeek string) (week string) {
  801. switch updateWeek {
  802. case "Monday":
  803. week = "周一"
  804. case "Tuesday":
  805. week = "周二"
  806. case "Wednesday":
  807. week = "周三"
  808. case "Thursday":
  809. week = "周四"
  810. case "Friday":
  811. week = "周五"
  812. case "Saturday":
  813. week = "周六"
  814. case "Sunday":
  815. week = "周日"
  816. }
  817. return week
  818. }
  819. func GetWeekDay() (string, string) {
  820. now := time.Now()
  821. offset := int(time.Monday - now.Weekday())
  822. //周日做特殊判断 因为time.Monday = 0
  823. if offset > 0 {
  824. offset = -6
  825. }
  826. lastoffset := int(time.Saturday - now.Weekday())
  827. //周日做特殊判断 因为time.Monday = 0
  828. if lastoffset == 6 {
  829. lastoffset = -1
  830. }
  831. firstOfWeek := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
  832. lastOfWeeK := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, lastoffset+1)
  833. f := firstOfWeek.Unix()
  834. l := lastOfWeeK.Unix()
  835. return time.Unix(f, 0).Format("2006-01-02") + " 00:00:00", time.Unix(l, 0).Format("2006-01-02") + " 23:59:59"
  836. }
  837. // GetOracleInReplace 获取oracle sql的in查询替换:1的方法
  838. func GetOracleInReplace(num int) string {
  839. template := make([]string, num)
  840. for i := 0; i < num; i++ {
  841. template[i] = ":1"
  842. }
  843. return strings.Join(template, ",")
  844. }
  845. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该Int值)
  846. func InArrayByInt(idStrList []int, searchId int) (has bool) {
  847. for _, id := range idStrList {
  848. if id == searchId {
  849. has = true
  850. return
  851. }
  852. }
  853. return
  854. }
  855. // IsErrNoRow
  856. // @Description: 判断是否是gorm的查询不到数据的报错
  857. // @param err
  858. // @return bool
  859. func IsErrNoRow(err error) bool {
  860. if err == nil {
  861. return false
  862. }
  863. return errors.Is(err, gorm.ErrRecordNotFound)
  864. }
  865. // ContainsWholeWord
  866. // @Description: 匹配是否存在该单词
  867. // @author: Roc
  868. // @datetime 2024-09-30 13:59:45
  869. // @param s string
  870. // @param word string
  871. // @return bool
  872. func ContainsWholeWord(s string, word string) bool {
  873. pattern := fmt.Sprintf(`\b%s\b`, regexp.QuoteMeta(word))
  874. re := regexp.MustCompile(pattern)
  875. return re.MatchString(s)
  876. }