common.go 26 KB

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