common.go 23 KB

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