common.go 28 KB

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