common.go 28 KB

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