common.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "github.com/astaxie/beego/logs"
  12. "github.com/dgrijalva/jwt-go"
  13. "gorm.io/gorm"
  14. "image"
  15. "image/png"
  16. "io"
  17. "math"
  18. "math/rand"
  19. "net/http"
  20. "os"
  21. "os/exec"
  22. "path"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. "time"
  27. )
  28. var ErrNoRow = gorm.ErrRecordNotFound
  29. var (
  30. KEY = []byte("5Mb5Gdmb5y")
  31. )
  32. func GenToken(account string) string {
  33. token := jwt.New(jwt.SigningMethodHS256)
  34. token.Claims = &jwt.StandardClaims{
  35. NotBefore: int64(time.Now().Unix()),
  36. ExpiresAt: int64(time.Now().Unix() + 90*24*60*60),
  37. Issuer: "hongze_admin",
  38. Subject: account,
  39. }
  40. ss, err := token.SignedString(KEY)
  41. if err != nil {
  42. logs.Error(err)
  43. return ""
  44. }
  45. return ss
  46. }
  47. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  48. func GetRandString(size int) string {
  49. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  50. randomSb := ""
  51. digitSize := len(allLetterDigit)
  52. for i := 0; i < size; i++ {
  53. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  54. }
  55. return randomSb
  56. }
  57. func GetRandStringNoSpecialChar(size int) string {
  58. 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"}
  59. randomSb := ""
  60. digitSize := len(allLetterDigit)
  61. for i := 0; i < size; i++ {
  62. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  63. }
  64. return randomSb
  65. }
  66. func StringsToJSON(str string) string {
  67. rs := []rune(str)
  68. jsons := ""
  69. for _, r := range rs {
  70. rint := int(r)
  71. if rint < 128 {
  72. jsons += string(r)
  73. } else {
  74. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  75. }
  76. }
  77. return jsons
  78. }
  79. func ToString(v interface{}) string {
  80. data, _ := json.Marshal(v)
  81. return string(data)
  82. }
  83. func MD5(data string) string {
  84. m := md5.Sum([]byte(data))
  85. return hex.EncodeToString(m[:])
  86. }
  87. func GetRandDigit(n int) string {
  88. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  89. }
  90. func GetRandNumber(n int) int {
  91. return rnd.Intn(n)
  92. }
  93. func GetRandInt(min, max int) int {
  94. if min >= max || min == 0 || max == 0 {
  95. return max
  96. }
  97. return rand.Intn(max-min) + min
  98. }
  99. func GetToday(format string) string {
  100. today := time.Now().Format(format)
  101. return today
  102. }
  103. func GetTodayLastSecond() time.Duration {
  104. today := GetToday(FormatDate) + " 23:59:59"
  105. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  106. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  107. }
  108. func GetBrithDate(idcard string) string {
  109. l := len(idcard)
  110. var s string
  111. if l == 15 {
  112. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  113. return s
  114. }
  115. if l == 18 {
  116. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  117. return s
  118. }
  119. return GetToday(FormatDate)
  120. }
  121. func WhichSexByIdcard(idcard string) string {
  122. var sexs = [2]string{"女", "男"}
  123. length := len(idcard)
  124. if length == 18 {
  125. sex, _ := strconv.Atoi(string(idcard[16]))
  126. return sexs[sex%2]
  127. } else if length == 15 {
  128. sex, _ := strconv.Atoi(string(idcard[14]))
  129. return sexs[sex%2]
  130. }
  131. return "男"
  132. }
  133. func SubFloatToString(f float64, m int) string {
  134. n := strconv.FormatFloat(f, 'f', -1, 64)
  135. if n == "" {
  136. return ""
  137. }
  138. if m >= len(n) {
  139. return n
  140. }
  141. newn := strings.Split(n, ".")
  142. if m == 0 {
  143. return newn[0]
  144. }
  145. if len(newn) < 2 || m >= len(newn[1]) {
  146. return n
  147. }
  148. return newn[0] + "." + newn[1][:m]
  149. }
  150. func SubFloatToFloat(f float64, m int) float64 {
  151. newn := SubFloatToString(f, m)
  152. newf, _ := strconv.ParseFloat(newn, 64)
  153. return newf
  154. }
  155. func SubFloatToFloatStr(f float64, m int) string {
  156. newn := SubFloatToString(f, m)
  157. return newn
  158. }
  159. func GetYearDiffer(start_time, end_time string) int {
  160. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  161. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  162. age := t2.Year() - t1.Year()
  163. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  164. age--
  165. }
  166. return age
  167. }
  168. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  169. diff := end_time.Unix() - start_time.Unix()
  170. return diff
  171. }
  172. func FixFloat(f float64, m int) float64 {
  173. newn := SubFloatToString(f+0.00000001, m)
  174. newf, _ := strconv.ParseFloat(newn, 64)
  175. return newf
  176. }
  177. func StrListToString(strList []string) (str string) {
  178. if len(strList) > 0 {
  179. for k, v := range strList {
  180. if k == 0 {
  181. str = v
  182. } else {
  183. str = str + "," + v
  184. }
  185. }
  186. return
  187. }
  188. return ""
  189. }
  190. func ValidateEmailFormatat(email string) bool {
  191. reg := regexp.MustCompile(RegularEmail)
  192. return reg.MatchString(email)
  193. }
  194. func ValidateMobileFormatat(mobileNum string) bool {
  195. reg := regexp.MustCompile(RegularMobile)
  196. return reg.MatchString(mobileNum)
  197. }
  198. func FileIsExist(filePath string) bool {
  199. _, err := os.Stat(filePath)
  200. return err == nil || os.IsExist(err)
  201. }
  202. func GetImgExt(file string) (ext string, err error) {
  203. var headerByte []byte
  204. headerByte = make([]byte, 8)
  205. fd, err := os.Open(file)
  206. if err != nil {
  207. return "", err
  208. }
  209. defer fd.Close()
  210. _, err = fd.Read(headerByte)
  211. if err != nil {
  212. return "", err
  213. }
  214. xStr := fmt.Sprintf("%x", headerByte)
  215. switch {
  216. case xStr == "89504e470d0a1a0a":
  217. ext = ".png"
  218. case xStr == "0000010001002020":
  219. ext = ".ico"
  220. case xStr == "0000020001002020":
  221. ext = ".cur"
  222. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  223. ext = ".gif"
  224. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  225. ext = ".tga"
  226. case xStr[:8] == "464f524d":
  227. ext = ".iff"
  228. case xStr[:8] == "52494646":
  229. ext = ".ani"
  230. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  231. ext = ".tiff"
  232. case xStr[:4] == "424d":
  233. ext = ".bmp"
  234. case xStr[:4] == "ffd8":
  235. ext = ".jpg"
  236. case xStr[:2] == "0a":
  237. ext = ".pcx"
  238. default:
  239. ext = ""
  240. }
  241. return ext, nil
  242. }
  243. func SaveImage(path string, img image.Image) (err error) {
  244. imgfile, err := os.Create(path)
  245. defer imgfile.Close()
  246. err = png.Encode(imgfile, img)
  247. return err
  248. }
  249. func DownloadImage(imgUrl string) (filePath string, err error) {
  250. imgPath := "./static/imgs/"
  251. fileName := path.Base(imgUrl)
  252. res, err := http.Get(imgUrl)
  253. if err != nil {
  254. fmt.Println("A error occurred!")
  255. return
  256. }
  257. defer res.Body.Close()
  258. reader := bufio.NewReaderSize(res.Body, 32*1024)
  259. filePath = imgPath + fileName
  260. file, err := os.Create(filePath)
  261. if err != nil {
  262. return
  263. }
  264. writer := bufio.NewWriter(file)
  265. written, _ := io.Copy(writer, reader)
  266. fmt.Printf("Total length: %d \n", written)
  267. return
  268. }
  269. func SaveBase64ToFile(content, path string) error {
  270. data, err := base64.StdEncoding.DecodeString(content)
  271. if err != nil {
  272. return err
  273. }
  274. f, err := os.Create(path)
  275. defer f.Close()
  276. if err != nil {
  277. return err
  278. }
  279. f.Write(data)
  280. return nil
  281. }
  282. func SaveBase64ToFileBySeek(content, path string) (err error) {
  283. data, err := base64.StdEncoding.DecodeString(content)
  284. exist, err := PathExists(path)
  285. if err != nil {
  286. return
  287. }
  288. if !exist {
  289. f, err := os.Create(path)
  290. if err != nil {
  291. return err
  292. }
  293. n, _ := f.Seek(0, 2)
  294. _, err = f.WriteAt([]byte(data), n)
  295. defer f.Close()
  296. } else {
  297. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  298. if err != nil {
  299. return err
  300. }
  301. n, _ := f.Seek(0, 2)
  302. _, err = f.WriteAt([]byte(data), n)
  303. defer f.Close()
  304. }
  305. return nil
  306. }
  307. func StartIndex(page, pagesize int) int {
  308. if page > 1 {
  309. return (page - 1) * pagesize
  310. }
  311. return 0
  312. }
  313. func PageCount(count, pagesize int) int {
  314. if count%pagesize > 0 {
  315. return count/pagesize + 1
  316. } else {
  317. return count / pagesize
  318. }
  319. }
  320. func TrimHtml(src string) string {
  321. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  322. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  323. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  324. src = re.ReplaceAllString(src, "")
  325. re, _ = regexp.Compile("class[\\S\\s]+?>")
  326. src = re.ReplaceAllString(src, "")
  327. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  328. src = re.ReplaceAllString(src, "")
  329. return strings.TrimSpace(src)
  330. }
  331. func TimeToTimestamp() {
  332. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  333. }
  334. func TimeTransferString(format string, t time.Time) string {
  335. str := t.Format(format)
  336. var emptyT time.Time
  337. if str == emptyT.Format(format) {
  338. return ""
  339. }
  340. return str
  341. }
  342. func ToUnicode(text string) string {
  343. textQuoted := strconv.QuoteToASCII(text)
  344. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  345. return textUnquoted
  346. }
  347. func VersionToInt(version string) int {
  348. version = strings.Replace(version, ".", "", -1)
  349. n, _ := strconv.Atoi(version)
  350. return n
  351. }
  352. func IsCheckInList(list []int, s int) bool {
  353. for _, v := range list {
  354. if v == s {
  355. return true
  356. }
  357. }
  358. return false
  359. }
  360. func round(num float64) int {
  361. return int(num + math.Copysign(0.5, num))
  362. }
  363. func toFixed(num float64, precision int) float64 {
  364. output := math.Pow(10, float64(precision))
  365. return float64(round(num*output)) / output
  366. }
  367. func GetWilsonScore(p, n float64) float64 {
  368. if p == 0 && n == 0 {
  369. return 0
  370. }
  371. 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)
  372. }
  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. func ConvertToFormatDay(excelDaysString string) string {
  497. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  498. curDiffDay := excelDaysString
  499. b, _ := strconv.Atoi(curDiffDay)
  500. realDiffDay := b - baseDiffDay
  501. realDiffSecond := realDiffDay * 24 * 3600
  502. baseOriginSecond := 1136185445
  503. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  504. return resultTime
  505. }
  506. func CheckPwd(pwd string) bool {
  507. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  508. reg := regexp.MustCompile(compile)
  509. flag := reg.MatchString(pwd)
  510. return flag
  511. }
  512. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  513. if len(myMonth) == 1 {
  514. myMonth = "0" + myMonth
  515. }
  516. yInt, _ := strconv.Atoi(myYear)
  517. timeLayout := "2006-01-02 15:04:05"
  518. loc, _ := time.LoadLocation("Local")
  519. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  520. newMonth := theTime.Month()
  521. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  522. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  523. return t1, t2
  524. }
  525. func TrimStr(str string) (str2 string) {
  526. return strings.Replace(str, " ", "", -1)
  527. }
  528. func StrTimeToTime(strTime string) time.Time {
  529. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  530. loc, _ := time.LoadLocation("Local") //重要:获取时区
  531. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  532. return resultTime
  533. }
  534. func StrDateTimeToWeek(strTime string) string {
  535. var WeekDayMap = map[string]string{
  536. "Monday": "周一",
  537. "Tuesday": "周二",
  538. "Wednesday": "周三",
  539. "Thursday": "周四",
  540. "Friday": "周五",
  541. "Saturday": "周六",
  542. "Sunday": "周日",
  543. }
  544. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  545. startday, _ := time.Parse("2006-01-02", ctime)
  546. staweek_int := startday.Weekday().String()
  547. return WeekDayMap[staweek_int]
  548. }
  549. func TimeToStrYmd(time2 time.Time) string {
  550. var Ymd string
  551. year := time2.Year()
  552. month := time2.Format("1")
  553. day1 := time.Now().Day()
  554. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  555. return Ymd
  556. }
  557. func TimeRemoveHms(strTime string) string {
  558. var Ymd string
  559. var resultTime = StrTimeToTime(strTime)
  560. year := resultTime.Year()
  561. month := resultTime.Format("01")
  562. day1 := resultTime.Day()
  563. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  564. return Ymd
  565. }
  566. func ArticleLastTime(strTime string) string {
  567. var newTime string
  568. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  569. diffTime := time.Now().Unix() - stamp.Unix()
  570. if diffTime <= 60 {
  571. newTime = "当前"
  572. } else if diffTime < 60*60 {
  573. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  574. } else if diffTime < 24*60*60 {
  575. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  576. } else if diffTime < 30*24*60*60 {
  577. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  578. } else if diffTime < 12*30*24*60*60 {
  579. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  580. } else {
  581. newTime = "1年前"
  582. }
  583. return newTime
  584. }
  585. func ConvertNumToCny(num float64) (str string, err error) {
  586. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  587. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  588. s := sliceUnit[len(sliceUnit)-len(strNum):]
  589. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  590. for k, v := range strNum[:] {
  591. str = str + upperDigitUnit[string(v)] + s[k]
  592. }
  593. reg, err := regexp.Compile(`零角零分$`)
  594. str = reg.ReplaceAllString(str, "整")
  595. reg, err = regexp.Compile(`零角`)
  596. str = reg.ReplaceAllString(str, "零")
  597. reg, err = regexp.Compile(`零分$`)
  598. str = reg.ReplaceAllString(str, "整")
  599. reg, err = regexp.Compile(`零[仟佰拾]`)
  600. str = reg.ReplaceAllString(str, "零")
  601. reg, err = regexp.Compile(`零{2,}`)
  602. str = reg.ReplaceAllString(str, "零")
  603. reg, err = regexp.Compile(`零亿`)
  604. str = reg.ReplaceAllString(str, "亿")
  605. reg, err = regexp.Compile(`零万`)
  606. str = reg.ReplaceAllString(str, "万")
  607. reg, err = regexp.Compile(`零*元`)
  608. str = reg.ReplaceAllString(str, "元")
  609. reg, err = regexp.Compile(`亿零{0, 3}万`)
  610. str = reg.ReplaceAllString(str, "^元")
  611. reg, err = regexp.Compile(`零元`)
  612. str = reg.ReplaceAllString(str, "零")
  613. return
  614. }
  615. func GetNowWeekMonday() time.Time {
  616. offset := int(time.Monday - time.Now().Weekday())
  617. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  618. offset = -6
  619. }
  620. mondayTime := time.Now().AddDate(0, 0, offset)
  621. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  622. return mondayTime
  623. }
  624. func GetNowWeekLastDay() time.Time {
  625. offset := int(time.Monday - time.Now().Weekday())
  626. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  627. offset = -6
  628. }
  629. firstDayTime := time.Now().AddDate(0, 0, offset)
  630. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  631. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  632. return lastDayTime
  633. }
  634. func GetNowMonthFirstDay() time.Time {
  635. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  636. return nowMonthFirstDay
  637. }
  638. func GetNowMonthLastDay() time.Time {
  639. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  640. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  641. return nowMonthLastDay
  642. }
  643. func GetNowQuarterFirstDay() time.Time {
  644. month := int(time.Now().Month())
  645. var nowQuarterFirstDay time.Time
  646. if month >= 1 && month <= 3 {
  647. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  648. } else if month >= 4 && month <= 6 {
  649. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  650. } else if month >= 7 && month <= 9 {
  651. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  652. } else {
  653. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  654. }
  655. return nowQuarterFirstDay
  656. }
  657. func GetNowQuarterLastDay() time.Time {
  658. month := int(time.Now().Month())
  659. var nowQuarterLastDay time.Time
  660. if month >= 1 && month <= 3 {
  661. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  662. } else if month >= 4 && month <= 6 {
  663. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  664. } else if month >= 7 && month <= 9 {
  665. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  666. } else {
  667. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  668. }
  669. return nowQuarterLastDay
  670. }
  671. func GetNowHalfYearFirstDay() time.Time {
  672. month := int(time.Now().Month())
  673. var nowHalfYearLastDay time.Time
  674. if month >= 1 && month <= 6 {
  675. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  676. } else {
  677. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  678. }
  679. return nowHalfYearLastDay
  680. }
  681. func GetNowHalfYearLastDay() time.Time {
  682. month := int(time.Now().Month())
  683. var nowHalfYearLastDay time.Time
  684. if month >= 1 && month <= 6 {
  685. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  686. } else {
  687. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  688. }
  689. return nowHalfYearLastDay
  690. }
  691. func GetNowYearFirstDay() time.Time {
  692. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  693. return nowYearFirstDay
  694. }
  695. func GetNowYearLastDay() time.Time {
  696. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  697. return nowYearLastDay
  698. }
  699. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  700. numYear := endDate.Year() - startDate.Year()
  701. numMonth := int(endDate.Month()) - int(startDate.Month())
  702. numDay := 0
  703. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  704. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  705. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  706. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  707. if endDate.Day() == endDateDays {
  708. numDay = startDateMonthDays - startDate.Day() + 1
  709. if numDay == startDateMonthDays {
  710. numMonth++
  711. numDay = 0
  712. if numMonth == 12 {
  713. numYear++
  714. numMonth = 0
  715. }
  716. }
  717. } else {
  718. numDay = endDate.Day() - startDate.Day() + 1
  719. }
  720. if numDay < 0 {
  721. numDay += endDatePrevMonthDays
  722. numMonth = numMonth - 1
  723. }
  724. if numMonth < 0 {
  725. numMonth += 12
  726. numYear = numYear - 1
  727. }
  728. if numYear < 0 {
  729. err = errors.New("日期异常")
  730. return
  731. }
  732. if numYear > 0 {
  733. beetweenDay += fmt.Sprint(numYear, "年")
  734. }
  735. if numMonth > 0 {
  736. beetweenDay += fmt.Sprint(numMonth, "个月")
  737. }
  738. if numDay > 0 {
  739. beetweenDay += fmt.Sprint(numDay, "天")
  740. }
  741. return
  742. }
  743. func getMonthDay(year, month int) (days int) {
  744. if month != 2 {
  745. if month == 4 || month == 6 || month == 9 || month == 11 {
  746. days = 30
  747. } else {
  748. days = 31
  749. }
  750. } else {
  751. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  752. days = 29
  753. } else {
  754. days = 28
  755. }
  756. }
  757. return
  758. }
  759. func InArray(needle interface{}, hyStack interface{}) bool {
  760. switch key := needle.(type) {
  761. case string:
  762. for _, item := range hyStack.([]string) {
  763. if key == item {
  764. return true
  765. }
  766. }
  767. case int:
  768. for _, item := range hyStack.([]int) {
  769. if key == item {
  770. return true
  771. }
  772. }
  773. case int64:
  774. for _, item := range hyStack.([]int64) {
  775. if key == item {
  776. return true
  777. }
  778. }
  779. default:
  780. return false
  781. }
  782. return false
  783. }
  784. func Bit2MB(bitSize int64, prec int) (size float64) {
  785. mb := float64(bitSize) / float64(1024*1024)
  786. size, _ = strconv.ParseFloat(strconv.FormatFloat(mb, 'f', prec, 64), 64)
  787. return
  788. }
  789. func SubStr(str string, subLen int) string {
  790. strRune := []rune(str)
  791. bodyRuneLen := len(strRune)
  792. if bodyRuneLen > subLen {
  793. bodyRuneLen = subLen
  794. }
  795. str = string(strRune[:bodyRuneLen])
  796. return str
  797. }
  798. func GetUpdateWeekEn(updateWeek string) string {
  799. switch updateWeek {
  800. case "周一":
  801. updateWeek = "monday"
  802. case "周二":
  803. updateWeek = "tuesday"
  804. case "周三":
  805. updateWeek = "wednesday"
  806. case "周四":
  807. updateWeek = "thursday"
  808. case "周五":
  809. updateWeek = "friday"
  810. case "周六":
  811. updateWeek = "saturday"
  812. case "周日":
  813. updateWeek = "sunday"
  814. }
  815. return updateWeek
  816. }
  817. func GetWeekZn(updateWeek string) (week string) {
  818. switch updateWeek {
  819. case "Monday":
  820. week = "周一"
  821. case "Tuesday":
  822. week = "周二"
  823. case "Wednesday":
  824. week = "周三"
  825. case "Thursday":
  826. week = "周四"
  827. case "Friday":
  828. week = "周五"
  829. case "Saturday":
  830. week = "周六"
  831. case "Sunday":
  832. week = "周日"
  833. }
  834. return week
  835. }
  836. func GetWeekDay() (string, string) {
  837. now := time.Now()
  838. offset := int(time.Monday - now.Weekday())
  839. if offset > 0 {
  840. offset = -6
  841. }
  842. lastoffset := int(time.Saturday - now.Weekday())
  843. if lastoffset == 6 {
  844. lastoffset = -1
  845. }
  846. firstOfWeek := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
  847. lastOfWeeK := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, lastoffset+1)
  848. f := firstOfWeek.Unix()
  849. l := lastOfWeeK.Unix()
  850. return time.Unix(f, 0).Format("2006-01-02") + " 00:00:00", time.Unix(l, 0).Format("2006-01-02") + " 23:59:59"
  851. }
  852. func GetOracleInReplace(num int) string {
  853. template := make([]string, num)
  854. for i := 0; i < num; i++ {
  855. template[i] = ":1"
  856. }
  857. return strings.Join(template, ",")
  858. }
  859. func InArrayByInt(idStrList []int, searchId int) (has bool) {
  860. for _, id := range idStrList {
  861. if id == searchId {
  862. has = true
  863. return
  864. }
  865. }
  866. return
  867. }
  868. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  869. for _, id := range idStrList {
  870. if id == searchId {
  871. has = true
  872. return
  873. }
  874. }
  875. return
  876. }
  877. func IsErrNoRow(err error) bool {
  878. if err == nil {
  879. return false
  880. }
  881. return errors.Is(err, gorm.ErrRecordNotFound)
  882. }