common.go 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "gorm.io/gorm"
  12. "image"
  13. "image/png"
  14. "io"
  15. "math"
  16. "math/rand"
  17. "net"
  18. "net/http"
  19. "os"
  20. "os/exec"
  21. "path"
  22. "regexp"
  23. "strconv"
  24. "strings"
  25. "time"
  26. )
  27. var ErrNoRow = gorm.ErrRecordNotFound
  28. /*var (
  29. KEY = []byte("OsL5s35Xv6")
  30. )*/
  31. // 发放token
  32. func GenToken(account string)(accessToken string, err error) {
  33. /*token := jwt.New(jwt.SigningMethodHS256)
  34. token.Claims = &jwt.StandardClaims{
  35. NotBefore: int64(time.Now().Unix()),
  36. ExpiresAt: int64(time.Now().Unix() + 90*24*60*60),
  37. Issuer: "hrms_api",
  38. Subject: account,
  39. }
  40. accessToken, err = token.SignedString(KEY)*/
  41. timeUnix := time.Now().Unix()
  42. timeUnixStr := strconv.FormatInt(timeUnix, 10)
  43. accessToken = MD5(account) + MD5(timeUnixStr)
  44. return
  45. }
  46. //随机数种子
  47. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  48. // GetRandString 获取随机字符串
  49. func GetRandString(size int) string {
  50. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  51. randomSb := ""
  52. digitSize := len(allLetterDigit)
  53. for i := 0; i < size; i++ {
  54. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  55. }
  56. return randomSb
  57. }
  58. // GetRandStringNoSpecialChar
  59. func GetRandStringNoSpecialChar(size int) string {
  60. 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"}
  61. randomSb := ""
  62. digitSize := len(allLetterDigit)
  63. for i := 0; i < size; i++ {
  64. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  65. }
  66. return randomSb
  67. }
  68. // StringsToJSON
  69. func StringsToJSON(str string) string {
  70. rs := []rune(str)
  71. jsons := ""
  72. for _, r := range rs {
  73. rint := int(r)
  74. if rint < 128 {
  75. jsons += string(r)
  76. } else {
  77. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  78. }
  79. }
  80. return jsons
  81. }
  82. // ToString 序列化
  83. func ToString(v interface{}) string {
  84. data, _ := json.Marshal(v)
  85. return string(data)
  86. }
  87. // MD5 md5加密
  88. func MD5(data string) string {
  89. m := md5.Sum([]byte(data))
  90. return hex.EncodeToString(m[:])
  91. }
  92. // GetRandDigit 获取数字随机字符
  93. func GetRandDigit(n int) string {
  94. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  95. }
  96. // GetRandNumber 获取随机数
  97. func GetRandNumber(n int) int {
  98. return rnd.Intn(n)
  99. }
  100. // GetRandInt
  101. func GetRandInt(min, max int) int {
  102. if min >= max || min == 0 || max == 0 {
  103. return max
  104. }
  105. return rand.Intn(max-min) + min
  106. }
  107. // GetToday 获取今天的随机字符
  108. func GetToday(format string) string {
  109. today := time.Now().Format(format)
  110. return today
  111. }
  112. // GetTodayLastSecond 获取今天剩余秒数
  113. func GetTodayLastSecond() time.Duration {
  114. today := GetToday(FormatDate) + " 23:59:59"
  115. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  116. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  117. }
  118. // GetBrithDate 处理出生日期函数
  119. func GetBrithDate(idcard string) string {
  120. l := len(idcard)
  121. var s string
  122. if l == 15 {
  123. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  124. return s
  125. }
  126. if l == 18 {
  127. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  128. return s
  129. }
  130. return GetToday(FormatDate)
  131. }
  132. // WhichSexByIdcard 处理性别
  133. func WhichSexByIdcard(idcard string) string {
  134. var sexs = [2]string{"女", "男"}
  135. length := len(idcard)
  136. if length == 18 {
  137. sex, _ := strconv.Atoi(string(idcard[16]))
  138. return sexs[sex%2]
  139. } else if length == 15 {
  140. sex, _ := strconv.Atoi(string(idcard[14]))
  141. return sexs[sex%2]
  142. }
  143. return "男"
  144. }
  145. // SubFloatToString 截取小数点后几位
  146. func SubFloatToString(f float64, m int) string {
  147. n := strconv.FormatFloat(f, 'f', -1, 64)
  148. if n == "" {
  149. return ""
  150. }
  151. if m >= len(n) {
  152. return n
  153. }
  154. newn := strings.Split(n, ".")
  155. if m == 0 {
  156. return newn[0]
  157. }
  158. if len(newn) < 2 || m >= len(newn[1]) {
  159. return n
  160. }
  161. return newn[0] + "." + newn[1][:m]
  162. }
  163. // SubFloatToFloat 截取小数点后几位
  164. func SubFloatToFloat(f float64, m int) float64 {
  165. newn := SubFloatToString(f, m)
  166. newf, _ := strconv.ParseFloat(newn, 64)
  167. return newf
  168. }
  169. // SubFloatToFloatStr 截取小数点后几位
  170. func SubFloatToFloatStr(f float64, m int) string {
  171. newn := SubFloatToString(f, m)
  172. return newn
  173. }
  174. // GetYearDiffer 获取相差时间-年
  175. func GetYearDiffer(start_time, end_time string) int {
  176. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  177. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  178. age := t2.Year() - t1.Year()
  179. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  180. age--
  181. }
  182. return age
  183. }
  184. // GetSecondDifferByTime 获取相差时间-秒
  185. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  186. diff := end_time.Unix() - start_time.Unix()
  187. return diff
  188. }
  189. // FixFloat
  190. func FixFloat(f float64, m int) float64 {
  191. newn := SubFloatToString(f+0.00000001, m)
  192. newf, _ := strconv.ParseFloat(newn, 64)
  193. return newf
  194. }
  195. // StrListToString 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  196. func StrListToString(strList []string) (str string) {
  197. if len(strList) > 0 {
  198. for k, v := range strList {
  199. if k == 0 {
  200. str = v
  201. } else {
  202. str = str + "," + v
  203. }
  204. }
  205. return
  206. }
  207. return ""
  208. }
  209. // ValidateEmailFormatat 校验邮箱格式
  210. func ValidateEmailFormatat(email string) bool {
  211. reg := regexp.MustCompile(RegularEmail)
  212. return reg.MatchString(email)
  213. }
  214. // ValidateMobileFormatat 验证是否是手机号
  215. func ValidateMobileFormatat(mobileNum string) bool {
  216. reg := regexp.MustCompile(RegularMobile)
  217. return reg.MatchString(mobileNum)
  218. }
  219. // FileIsExist 判断文件是否存在
  220. func FileIsExist(filePath string) bool {
  221. _, err := os.Stat(filePath)
  222. return err == nil || os.IsExist(err)
  223. }
  224. // GetImgExt 获取图片扩展名
  225. func GetImgExt(file string) (ext string, err error) {
  226. var headerByte []byte
  227. headerByte = make([]byte, 8)
  228. fd, err := os.Open(file)
  229. if err != nil {
  230. return "", err
  231. }
  232. defer fd.Close()
  233. _, err = fd.Read(headerByte)
  234. if err != nil {
  235. return "", err
  236. }
  237. xStr := fmt.Sprintf("%x", headerByte)
  238. switch {
  239. case xStr == "89504e470d0a1a0a":
  240. ext = ".png"
  241. case xStr == "0000010001002020":
  242. ext = ".ico"
  243. case xStr == "0000020001002020":
  244. ext = ".cur"
  245. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  246. ext = ".gif"
  247. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  248. ext = ".tga"
  249. case xStr[:8] == "464f524d":
  250. ext = ".iff"
  251. case xStr[:8] == "52494646":
  252. ext = ".ani"
  253. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  254. ext = ".tiff"
  255. case xStr[:4] == "424d":
  256. ext = ".bmp"
  257. case xStr[:4] == "ffd8":
  258. ext = ".jpg"
  259. case xStr[:2] == "0a":
  260. ext = ".pcx"
  261. default:
  262. ext = ""
  263. }
  264. return ext, nil
  265. }
  266. // SaveImage 保存图片
  267. func SaveImage(path string, img image.Image) (err error) {
  268. //需要保持的文件
  269. imgfile, err := os.Create(path)
  270. defer imgfile.Close()
  271. // 以PNG格式保存文件
  272. err = png.Encode(imgfile, img)
  273. return err
  274. }
  275. // DownloadImage 下载图片
  276. func DownloadImage(imgUrl string) (filePath string, err error) {
  277. imgPath := "./static/imgs/"
  278. fileName := path.Base(imgUrl)
  279. res, err := http.Get(imgUrl)
  280. if err != nil {
  281. fmt.Println("A error occurred!")
  282. return
  283. }
  284. defer res.Body.Close()
  285. // 获得get请求响应的reader对象
  286. reader := bufio.NewReaderSize(res.Body, 32*1024)
  287. filePath = imgPath + fileName
  288. file, err := os.Create(filePath)
  289. if err != nil {
  290. return
  291. }
  292. // 获得文件的writer对象
  293. writer := bufio.NewWriter(file)
  294. written, _ := io.Copy(writer, reader)
  295. fmt.Printf("Total length: %d \n", written)
  296. return
  297. }
  298. // SaveBase64ToFile 保存base64数据为文件
  299. func SaveBase64ToFile(content, path string) error {
  300. data, err := base64.StdEncoding.DecodeString(content)
  301. if err != nil {
  302. return err
  303. }
  304. f, err := os.Create(path)
  305. defer f.Close()
  306. if err != nil {
  307. return err
  308. }
  309. f.Write(data)
  310. return nil
  311. }
  312. // SaveBase64ToFileBySeek
  313. func SaveBase64ToFileBySeek(content, path string) (err error) {
  314. data, err := base64.StdEncoding.DecodeString(content)
  315. exist, err := PathExists(path)
  316. if err != nil {
  317. return
  318. }
  319. if !exist {
  320. f, err := os.Create(path)
  321. if err != nil {
  322. return err
  323. }
  324. n, _ := f.Seek(0, 2)
  325. // 从末尾的偏移量开始写入内容
  326. _, err = f.WriteAt([]byte(data), n)
  327. defer f.Close()
  328. } else {
  329. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  330. if err != nil {
  331. return err
  332. }
  333. n, _ := f.Seek(0, 2)
  334. // 从末尾的偏移量开始写入内容
  335. _, err = f.WriteAt([]byte(data), n)
  336. defer f.Close()
  337. }
  338. return nil
  339. }
  340. // StartIndex 开始下标
  341. func StartIndex(page, pagesize int) int {
  342. if page > 1 {
  343. return (page - 1) * pagesize
  344. }
  345. return 0
  346. }
  347. // PageCount
  348. func PageCount(count, pagesize int) int {
  349. if count%pagesize > 0 {
  350. return count/pagesize + 1
  351. } else {
  352. return count / pagesize
  353. }
  354. }
  355. // TrimHtml
  356. func TrimHtml(src string) string {
  357. //将HTML标签全转换成小写
  358. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  359. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  360. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  361. src = re.ReplaceAllString(src, "")
  362. re, _ = regexp.Compile("class[\\S\\s]+?>")
  363. src = re.ReplaceAllString(src, "")
  364. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  365. src = re.ReplaceAllString(src, "")
  366. return strings.TrimSpace(src)
  367. }
  368. //1556164246 -> 2019-04-25 03:50:46 +0000
  369. //timestamp
  370. // TimeToTimestamp
  371. func TimeToTimestamp() {
  372. fmt.Println(time.Unix(1556164246, 0).Format(FormatDateTime))
  373. }
  374. func TimeTransferString(format string, t time.Time) string {
  375. str := t.Format(format)
  376. var emptyT time.Time
  377. if str == emptyT.Format(format) {
  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) 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("2006-01-02")
  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. }