common.go 31 KB

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