common.go 28 KB

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