common.go 28 KB

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