common.go 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. if t.IsZero() {
  378. return ""
  379. }
  380. return str
  381. }
  382. // ToUnicode
  383. func ToUnicode(text string) string {
  384. textQuoted := strconv.QuoteToASCII(text)
  385. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  386. return textUnquoted
  387. }
  388. // VersionToInt
  389. func VersionToInt(version string) int {
  390. version = strings.Replace(version, ".", "", -1)
  391. n, _ := strconv.Atoi(version)
  392. return n
  393. }
  394. // IsCheckInList
  395. func IsCheckInList(list []int, s int) bool {
  396. for _, v := range list {
  397. if v == s {
  398. return true
  399. }
  400. }
  401. return false
  402. }
  403. // round
  404. func round(num float64) int {
  405. return int(num + math.Copysign(0.5, num))
  406. }
  407. // toFixed
  408. func toFixed(num float64, precision int) float64 {
  409. output := math.Pow(10, float64(precision))
  410. return float64(round(num*output)) / output
  411. }
  412. // GetWilsonScore returns Wilson Score
  413. func GetWilsonScore(p, n float64) float64 {
  414. if p == 0 && n == 0 {
  415. return 0
  416. }
  417. 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)
  418. }
  419. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  420. func ChangeWordsToNum(str string) (numStr string) {
  421. words := ([]rune)(str)
  422. num := 0
  423. n := 0
  424. for i := 0; i < len(words); i++ {
  425. word := string(words[i : i+1])
  426. switch word {
  427. case "万":
  428. if n == 0 {
  429. n = 1
  430. }
  431. n = n * 10000
  432. num = num*10000 + n
  433. n = 0
  434. case "千":
  435. if n == 0 {
  436. n = 1
  437. }
  438. n = n * 1000
  439. num += n
  440. n = 0
  441. case "百":
  442. if n == 0 {
  443. n = 1
  444. }
  445. n = n * 100
  446. num += n
  447. n = 0
  448. case "十":
  449. if n == 0 {
  450. n = 1
  451. }
  452. n = n * 10
  453. num += n
  454. n = 0
  455. case "一":
  456. n += 1
  457. case "二":
  458. n += 2
  459. case "三":
  460. n += 3
  461. case "四":
  462. n += 4
  463. case "五":
  464. n += 5
  465. case "六":
  466. n += 6
  467. case "七":
  468. n += 7
  469. case "八":
  470. n += 8
  471. case "九":
  472. n += 9
  473. case "零":
  474. default:
  475. if n > 0 {
  476. num += n
  477. n = 0
  478. }
  479. if num == 0 {
  480. numStr += word
  481. } else {
  482. numStr += strconv.Itoa(num) + word
  483. num = 0
  484. }
  485. }
  486. }
  487. if n > 0 {
  488. num += n
  489. n = 0
  490. }
  491. if num != 0 {
  492. numStr += strconv.Itoa(num)
  493. }
  494. return
  495. }
  496. // Sha1
  497. func Sha1(data string) string {
  498. sha1 := sha1.New()
  499. sha1.Write([]byte(data))
  500. return hex.EncodeToString(sha1.Sum([]byte("")))
  501. }
  502. // GetVideoPlaySeconds
  503. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  504. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  505. out, err := exec.Command("bash", "-c", cmd).Output()
  506. if err != nil {
  507. return
  508. }
  509. outTimes := string(out)
  510. fmt.Println("outTimes:", outTimes)
  511. if outTimes != "" {
  512. timeArr := strings.Split(outTimes, ":")
  513. h := timeArr[0]
  514. m := timeArr[1]
  515. s := timeArr[2]
  516. hInt, err := strconv.Atoi(h)
  517. if err != nil {
  518. return playSeconds, err
  519. }
  520. mInt, err := strconv.Atoi(m)
  521. if err != nil {
  522. return playSeconds, err
  523. }
  524. s = strings.Trim(s, " ")
  525. s = strings.Trim(s, "\n")
  526. sInt, err := strconv.ParseFloat(s, 64)
  527. if err != nil {
  528. return playSeconds, err
  529. }
  530. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  531. }
  532. return
  533. }
  534. // GetMaxTradeCode
  535. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  536. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  537. tradeCode = strings.Trim(tradeCode, " ")
  538. tradeCodeInt, err := strconv.Atoi(tradeCode)
  539. if err != nil {
  540. return
  541. }
  542. tradeCodeInt = tradeCodeInt + 1
  543. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  544. return
  545. }
  546. // ConvertToFormatDay excel日期字段格式化 yyyy-mm-dd
  547. func ConvertToFormatDay(excelDaysString string, tFormat string) string {
  548. // 2006-01-02 距离 1900-01-01的天数
  549. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  550. curDiffDay := excelDaysString
  551. b, _ := strconv.Atoi(curDiffDay)
  552. // 获取excel的日期距离2006-01-02的天数
  553. realDiffDay := b - baseDiffDay
  554. //fmt.Println("realDiffDay:",realDiffDay)
  555. // 距离2006-01-02 秒数
  556. realDiffSecond := realDiffDay * 24 * 3600
  557. //fmt.Println("realDiffSecond:",realDiffSecond)
  558. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  559. baseOriginSecond := 1136185445
  560. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format(tFormat)
  561. return resultTime
  562. }
  563. // CheckPwd
  564. func CheckPwd(pwd string) bool {
  565. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  566. reg := regexp.MustCompile(compile)
  567. flag := reg.MatchString(pwd)
  568. return flag
  569. }
  570. // GetMonthStartAndEnd
  571. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  572. // 数字月份必须前置补零
  573. if len(myMonth) == 1 {
  574. myMonth = "0" + myMonth
  575. }
  576. yInt, _ := strconv.Atoi(myYear)
  577. timeLayout := FormatDateTime
  578. loc, _ := time.LoadLocation("Local")
  579. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  580. newMonth := theTime.Month()
  581. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  582. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  583. return t1, t2
  584. }
  585. // TrimStr 移除字符串中的空格
  586. func TrimStr(str string) (str2 string) {
  587. return strings.Replace(str, " ", "", -1)
  588. }
  589. // StrTimeToTime 字符串转换为time
  590. func StrTimeToTime(strTime string) time.Time {
  591. timeLayout := FormatDateTime //转化所需模板
  592. loc, _ := time.LoadLocation("Local") //重要:获取时区
  593. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  594. return resultTime
  595. }
  596. // StrDateTimeToWeek 字符串类型时间转周几
  597. func StrDateTimeToWeek(strTime string) string {
  598. var WeekDayMap = map[string]string{
  599. "Monday": "周一",
  600. "Tuesday": "周二",
  601. "Wednesday": "周三",
  602. "Thursday": "周四",
  603. "Friday": "周五",
  604. "Saturday": "周六",
  605. "Sunday": "周日",
  606. }
  607. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  608. startday, _ := time.Parse("2006-01-02", ctime)
  609. staweek_int := startday.Weekday().String()
  610. return WeekDayMap[staweek_int]
  611. }
  612. // TimeToStrYmd 时间格式转年月日字符串
  613. func TimeToStrYmd(time2 time.Time) string {
  614. var Ymd string
  615. year := time2.Year()
  616. month := time2.Format("1")
  617. day1 := time.Now().Day()
  618. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  619. return Ymd
  620. }
  621. // TimeRemoveHms 时间格式去掉时分秒
  622. func TimeRemoveHms(strTime string) string {
  623. var Ymd string
  624. var resultTime = StrTimeToTime(strTime)
  625. year := resultTime.Year()
  626. month := resultTime.Format("01")
  627. day1 := resultTime.Day()
  628. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  629. return Ymd
  630. }
  631. // ArticleLastTime 文章上一次编辑时间
  632. func ArticleLastTime(strTime string) string {
  633. var newTime string
  634. stamp, _ := time.ParseInLocation(FormatDateTime, strTime, time.Local)
  635. diffTime := time.Now().Unix() - stamp.Unix()
  636. if diffTime <= 60 {
  637. newTime = "当前"
  638. } else if diffTime < 60*60 {
  639. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  640. } else if diffTime < 24*60*60 {
  641. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  642. } else if diffTime < 30*24*60*60 {
  643. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  644. } else if diffTime < 12*30*24*60*60 {
  645. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  646. } else {
  647. newTime = "1年前"
  648. }
  649. return newTime
  650. }
  651. // ConvertNumToCny 人民币小写转大写
  652. func ConvertNumToCny(num float64) (str string, err error) {
  653. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  654. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  655. // log.Println(sliceUnit[:len(sliceUnit)-2])
  656. s := sliceUnit[len(sliceUnit)-len(strNum):]
  657. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  658. for k, v := range strNum[:] {
  659. str = str + upperDigitUnit[string(v)] + s[k]
  660. }
  661. reg, err := regexp.Compile(`零角零分$`)
  662. str = reg.ReplaceAllString(str, "整")
  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(`零{2,}`)
  670. str = reg.ReplaceAllString(str, "零")
  671. reg, err = regexp.Compile(`零亿`)
  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(`亿零{0, 3}万`)
  678. str = reg.ReplaceAllString(str, "^元")
  679. reg, err = regexp.Compile(`零元`)
  680. str = reg.ReplaceAllString(str, "零")
  681. return
  682. }
  683. // GetNowWeekMonday 获取本周周一的时间
  684. func GetNowWeekMonday() time.Time {
  685. offset := int(time.Monday - time.Now().Weekday())
  686. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  687. offset = -6
  688. }
  689. mondayTime := time.Now().AddDate(0, 0, offset)
  690. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  691. return mondayTime
  692. }
  693. // GetNowWeekLastDay 获取本周最后一天的时间
  694. func GetNowWeekLastDay() time.Time {
  695. offset := int(time.Monday - time.Now().Weekday())
  696. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  697. offset = -6
  698. }
  699. firstDayTime := time.Now().AddDate(0, 0, offset)
  700. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  701. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  702. return lastDayTime
  703. }
  704. // GetNowMonthFirstDay 获取本月第一天的时间
  705. func GetNowMonthFirstDay() time.Time {
  706. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  707. return nowMonthFirstDay
  708. }
  709. // GetNowMonthLastDay 获取本月最后一天的时间
  710. func GetNowMonthLastDay() time.Time {
  711. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  712. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  713. return nowMonthLastDay
  714. }
  715. // GetNowQuarterFirstDay 获取本季度第一天的时间
  716. func GetNowQuarterFirstDay() time.Time {
  717. month := int(time.Now().Month())
  718. var nowQuarterFirstDay time.Time
  719. if month >= 1 && month <= 3 {
  720. //1月1号
  721. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  722. } else if month >= 4 && month <= 6 {
  723. //4月1号
  724. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  725. } else if month >= 7 && month <= 9 {
  726. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  727. } else {
  728. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  729. }
  730. return nowQuarterFirstDay
  731. }
  732. // GetNowQuarterLastDay 获取本季度最后一天的时间
  733. func GetNowQuarterLastDay() time.Time {
  734. month := int(time.Now().Month())
  735. var nowQuarterLastDay time.Time
  736. if month >= 1 && month <= 3 {
  737. //03-31 23:59:59
  738. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  739. } else if month >= 4 && month <= 6 {
  740. //06-30 23:59:59
  741. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  742. } else if month >= 7 && month <= 9 {
  743. //09-30 23:59:59
  744. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  745. } else {
  746. //12-31 23:59:59
  747. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  748. }
  749. return nowQuarterLastDay
  750. }
  751. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  752. func GetNowHalfYearFirstDay() time.Time {
  753. month := int(time.Now().Month())
  754. var nowHalfYearLastDay time.Time
  755. if month >= 1 && month <= 6 {
  756. //03-31 23:59:59
  757. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  758. } else {
  759. //12-31 23:59:59
  760. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  761. }
  762. return nowHalfYearLastDay
  763. }
  764. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  765. func GetNowHalfYearLastDay() time.Time {
  766. month := int(time.Now().Month())
  767. var nowHalfYearLastDay time.Time
  768. if month >= 1 && month <= 6 {
  769. //03-31 23:59:59
  770. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  771. } else {
  772. //12-31 23:59:59
  773. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  774. }
  775. return nowHalfYearLastDay
  776. }
  777. // GetNowYearFirstDay 获取当前年的最后一天的时间
  778. func GetNowYearFirstDay() time.Time {
  779. //12-31 23:59:59
  780. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  781. return nowYearFirstDay
  782. }
  783. // GetNowYearLastDay 获取当前年的最后一天的时间
  784. func GetNowYearLastDay() time.Time {
  785. //12-31 23:59:59
  786. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  787. return nowYearLastDay
  788. }
  789. // CalculationDate 计算两个日期之间相差n年m月y天
  790. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  791. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  792. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  793. numYear := endDate.Year() - startDate.Year()
  794. numMonth := int(endDate.Month()) - int(startDate.Month())
  795. numDay := 0
  796. //获取截止月的总天数
  797. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  798. //获取截止月的前一个月
  799. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  800. //获取截止日期的上一个月的总天数
  801. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  802. //获取开始日期的的月份总天数
  803. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  804. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  805. if endDate.Day() == endDateDays {
  806. numDay = startDateMonthDays - startDate.Day() + 1
  807. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  808. if numDay == startDateMonthDays {
  809. numMonth++
  810. numDay = 0
  811. //超过月份了,那么年份加1
  812. if numMonth == 12 {
  813. numYear++
  814. numMonth = 0
  815. }
  816. }
  817. } else {
  818. numDay = endDate.Day() - startDate.Day() + 1
  819. }
  820. //天数小于0,那么向月份借一位
  821. if numDay < 0 {
  822. //向上一个月借一个月的天数
  823. numDay += endDatePrevMonthDays
  824. //总月份减去一个月
  825. numMonth = numMonth - 1
  826. }
  827. //月份小于0,那么向年份借一位
  828. if numMonth < 0 {
  829. //向上一个年借12个月
  830. numMonth += 12
  831. //总年份减去一年
  832. numYear = numYear - 1
  833. }
  834. if numYear < 0 {
  835. err = errors.New("日期异常")
  836. return
  837. }
  838. if numYear > 0 {
  839. beetweenDay += fmt.Sprint(numYear, "年")
  840. }
  841. if numMonth > 0 {
  842. beetweenDay += fmt.Sprint(numMonth, "个月")
  843. }
  844. if numDay > 0 {
  845. beetweenDay += fmt.Sprint(numDay, "天")
  846. }
  847. return
  848. }
  849. // getMonthDay 获取某年某月有多少天
  850. func getMonthDay(year, month int) (days int) {
  851. if month != 2 {
  852. if month == 4 || month == 6 || month == 9 || month == 11 {
  853. days = 30
  854. } else {
  855. days = 31
  856. }
  857. } else {
  858. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  859. days = 29
  860. } else {
  861. days = 28
  862. }
  863. }
  864. return
  865. }
  866. // InArray 是否在切片(数组/map)中含有该值,目前只支持:string、int 、 int64,其他都是返回false
  867. func InArray(needle interface{}, hyStack interface{}) bool {
  868. switch key := needle.(type) {
  869. case string:
  870. for _, item := range hyStack.([]string) {
  871. if key == item {
  872. return true
  873. }
  874. }
  875. case int:
  876. for _, item := range hyStack.([]int) {
  877. if key == item {
  878. return true
  879. }
  880. }
  881. case int64:
  882. for _, item := range hyStack.([]int64) {
  883. if key == item {
  884. return true
  885. }
  886. }
  887. default:
  888. return false
  889. }
  890. return false
  891. }
  892. // bit转MB 保留小数
  893. func Bit2MB(bitSize int64, prec int) (size float64) {
  894. mb := float64(bitSize) / float64(1024*1024)
  895. size, _ = strconv.ParseFloat(strconv.FormatFloat(mb, 'f', prec, 64), 64)
  896. return
  897. }
  898. // SubStr 截取字符串(中文)
  899. func SubStr(str string, subLen int) string {
  900. strRune := []rune(str)
  901. bodyRuneLen := len(strRune)
  902. if bodyRuneLen > subLen {
  903. bodyRuneLen = subLen
  904. }
  905. str = string(strRune[:bodyRuneLen])
  906. return str
  907. }
  908. func GetInterfaceAddrs() (ip string) {
  909. addrs, err := net.InterfaceAddrs()
  910. if err != nil {
  911. fmt.Println(err)
  912. return
  913. }
  914. for _, address := range addrs {
  915. // 检查ip地址判断是否回环地址
  916. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  917. if ipnet.IP.To4() != nil {
  918. fmt.Println(ipnet.IP.String())
  919. ip = ipnet.IP.String()
  920. return
  921. }
  922. }
  923. }
  924. return
  925. }
  926. // JoinStr2IntArr 拼接字符串转[]int
  927. func JoinStr2IntArr(str, sep string) (arr []int) {
  928. arr = make([]int, 0)
  929. if str == "" {
  930. return
  931. }
  932. if sep == "" {
  933. sep = ","
  934. }
  935. strArr := strings.Split(str, sep)
  936. if len(strArr) == 0 {
  937. return
  938. }
  939. for i := range strArr {
  940. v, e := strconv.Atoi(strArr[i])
  941. // int2str此处过滤掉无效int
  942. if e != nil {
  943. continue
  944. }
  945. arr = append(arr, v)
  946. }
  947. return
  948. }
  949. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  950. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  951. for _, id := range idIntList {
  952. if id == searchId {
  953. has = true
  954. return
  955. }
  956. }
  957. return
  958. }
  959. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  960. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  961. for _, id := range idStrList {
  962. if id == searchId {
  963. has = true
  964. return
  965. }
  966. }
  967. return
  968. }
  969. // PublicGetRequest 公共Get请求方法
  970. func PublicGetRequest(url, authorization string) (body []byte, err error) {
  971. method := "GET"
  972. client := &http.Client{}
  973. req, err := http.NewRequest(method, url, nil)
  974. if err != nil {
  975. return
  976. }
  977. if authorization != "" {
  978. req.Header.Add("Authorization", authorization)
  979. }
  980. res, err := client.Do(req)
  981. if err != nil {
  982. return
  983. }
  984. defer func() {
  985. _ = res.Body.Close()
  986. }()
  987. body, err = ioutil.ReadAll(res.Body)
  988. if err != nil {
  989. return
  990. }
  991. return
  992. }