common.go 30 KB

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