common.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  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. // 数据没有记录
  186. func ErrNoRow() string {
  187. return "<QuerySeter> no row found"
  188. }
  189. // 判断文件是否存在
  190. func FileIsExist(filePath string) bool {
  191. _, err := os.Stat(filePath)
  192. return err == nil || os.IsExist(err)
  193. }
  194. // 获取图片扩展名
  195. func GetImgExt(file string) (ext string, err error) {
  196. var headerByte []byte
  197. headerByte = make([]byte, 8)
  198. fd, err := os.Open(file)
  199. if err != nil {
  200. return "", err
  201. }
  202. defer fd.Close()
  203. _, err = fd.Read(headerByte)
  204. if err != nil {
  205. return "", err
  206. }
  207. xStr := fmt.Sprintf("%x", headerByte)
  208. switch {
  209. case xStr == "89504e470d0a1a0a":
  210. ext = ".png"
  211. case xStr == "0000010001002020":
  212. ext = ".ico"
  213. case xStr == "0000020001002020":
  214. ext = ".cur"
  215. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  216. ext = ".gif"
  217. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  218. ext = ".tga"
  219. case xStr[:8] == "464f524d":
  220. ext = ".iff"
  221. case xStr[:8] == "52494646":
  222. ext = ".ani"
  223. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  224. ext = ".tiff"
  225. case xStr[:4] == "424d":
  226. ext = ".bmp"
  227. case xStr[:4] == "ffd8":
  228. ext = ".jpg"
  229. case xStr[:2] == "0a":
  230. ext = ".pcx"
  231. default:
  232. ext = ""
  233. }
  234. return ext, nil
  235. }
  236. // 保存图片
  237. func SaveImage(path string, img image.Image) (err error) {
  238. //需要保持的文件
  239. imgfile, err := os.Create(path)
  240. defer imgfile.Close()
  241. // 以PNG格式保存文件
  242. err = png.Encode(imgfile, img)
  243. return err
  244. }
  245. // 下载图片
  246. func DownloadImage(imgUrl string) (filePath string, err error) {
  247. imgPath := "./static/imgs/"
  248. fileName := path.Base(imgUrl)
  249. res, err := http.Get(imgUrl)
  250. if err != nil {
  251. fmt.Println("A error occurred!")
  252. return
  253. }
  254. defer res.Body.Close()
  255. // 获得get请求响应的reader对象
  256. reader := bufio.NewReaderSize(res.Body, 32*1024)
  257. filePath = imgPath + fileName
  258. file, err := os.Create(filePath)
  259. if err != nil {
  260. return
  261. }
  262. // 获得文件的writer对象
  263. writer := bufio.NewWriter(file)
  264. written, _ := io.Copy(writer, reader)
  265. fmt.Printf("Total length: %d \n", written)
  266. return
  267. }
  268. // 保存base64数据为文件
  269. func SaveBase64ToFile(content, path string) error {
  270. data, err := base64.StdEncoding.DecodeString(content)
  271. if err != nil {
  272. return err
  273. }
  274. f, err := os.Create(path)
  275. defer f.Close()
  276. if err != nil {
  277. return err
  278. }
  279. f.Write(data)
  280. return nil
  281. }
  282. func SaveBase64ToFileBySeek(content, path string) (err error) {
  283. data, err := base64.StdEncoding.DecodeString(content)
  284. exist, err := PathExists(path)
  285. if err != nil {
  286. return
  287. }
  288. if !exist {
  289. f, err := os.Create(path)
  290. if err != nil {
  291. return err
  292. }
  293. n, _ := f.Seek(0, 2)
  294. // 从末尾的偏移量开始写入内容
  295. _, err = f.WriteAt([]byte(data), n)
  296. defer f.Close()
  297. } else {
  298. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  299. if err != nil {
  300. return err
  301. }
  302. n, _ := f.Seek(0, 2)
  303. // 从末尾的偏移量开始写入内容
  304. _, err = f.WriteAt([]byte(data), n)
  305. defer f.Close()
  306. }
  307. return nil
  308. }
  309. func PathExists(path string) (bool, error) {
  310. _, err := os.Stat(path)
  311. if err == nil {
  312. return true, nil
  313. }
  314. if os.IsNotExist(err) {
  315. return false, nil
  316. }
  317. return false, err
  318. }
  319. func StartIndex(page, pagesize int) int {
  320. if page > 1 {
  321. return (page - 1) * pagesize
  322. }
  323. return 0
  324. }
  325. func PageCount(count, pagesize int) int {
  326. if count%pagesize > 0 {
  327. return count/pagesize + 1
  328. } else {
  329. return count / pagesize
  330. }
  331. }
  332. func TrimHtml(src string) string {
  333. //将HTML标签全转换成小写
  334. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  335. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  336. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  337. src = re.ReplaceAllString(src, "[图片]")
  338. re, _ = regexp.Compile("class[\\S\\s]+?>")
  339. src = re.ReplaceAllString(src, "")
  340. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  341. src = re.ReplaceAllString(src, "")
  342. return strings.TrimSpace(src)
  343. }
  344. //1556164246 -> 2019-04-25 03:50:46 +0000
  345. //timestamp
  346. func TimeToTimestamp() {
  347. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  348. }
  349. func ToUnicode(text string) string {
  350. textQuoted := strconv.QuoteToASCII(text)
  351. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  352. return textUnquoted
  353. }
  354. func VersionToInt(version string) int {
  355. version = strings.Replace(version, ".", "", -1)
  356. n, _ := strconv.Atoi(version)
  357. return n
  358. }
  359. func IsCheckInList(list []int, s int) bool {
  360. for _, v := range list {
  361. if v == s {
  362. return true
  363. }
  364. }
  365. return false
  366. }
  367. func round(num float64) int {
  368. return int(num + math.Copysign(0.5, num))
  369. }
  370. func toFixed(num float64, precision int) float64 {
  371. output := math.Pow(10, float64(precision))
  372. return float64(round(num*output)) / output
  373. }
  374. // GetWilsonScore returns Wilson Score
  375. func GetWilsonScore(p, n float64) float64 {
  376. if p == 0 && n == 0 {
  377. return 0
  378. }
  379. 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)
  380. }
  381. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  382. func ChangeWordsToNum(str string) (numStr string) {
  383. words := ([]rune)(str)
  384. num := 0
  385. n := 0
  386. for i := 0; i < len(words); i++ {
  387. word := string(words[i : i+1])
  388. switch word {
  389. case "万":
  390. if n == 0 {
  391. n = 1
  392. }
  393. n = n * 10000
  394. num = num*10000 + n
  395. n = 0
  396. case "千":
  397. if n == 0 {
  398. n = 1
  399. }
  400. n = n * 1000
  401. num += n
  402. n = 0
  403. case "百":
  404. if n == 0 {
  405. n = 1
  406. }
  407. n = n * 100
  408. num += n
  409. n = 0
  410. case "十":
  411. if n == 0 {
  412. n = 1
  413. }
  414. n = n * 10
  415. num += n
  416. n = 0
  417. case "一":
  418. n += 1
  419. case "二":
  420. n += 2
  421. case "三":
  422. n += 3
  423. case "四":
  424. n += 4
  425. case "五":
  426. n += 5
  427. case "六":
  428. n += 6
  429. case "七":
  430. n += 7
  431. case "八":
  432. n += 8
  433. case "九":
  434. n += 9
  435. case "零":
  436. default:
  437. if n > 0 {
  438. num += n
  439. n = 0
  440. }
  441. if num == 0 {
  442. numStr += word
  443. } else {
  444. numStr += strconv.Itoa(num) + word
  445. num = 0
  446. }
  447. }
  448. }
  449. if n > 0 {
  450. num += n
  451. n = 0
  452. }
  453. if num != 0 {
  454. numStr += strconv.Itoa(num)
  455. }
  456. return
  457. }
  458. func Sha1(data string) string {
  459. sha1 := sha1.New()
  460. sha1.Write([]byte(data))
  461. return hex.EncodeToString(sha1.Sum([]byte("")))
  462. }
  463. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  464. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  465. out, err := exec.Command("bash", "-c", cmd).Output()
  466. if err != nil {
  467. return
  468. }
  469. outTimes := string(out)
  470. fmt.Println("outTimes:", outTimes)
  471. if outTimes != "" {
  472. timeArr := strings.Split(outTimes, ":")
  473. h := timeArr[0]
  474. m := timeArr[1]
  475. s := timeArr[2]
  476. hInt, err := strconv.Atoi(h)
  477. if err != nil {
  478. return playSeconds, err
  479. }
  480. mInt, err := strconv.Atoi(m)
  481. if err != nil {
  482. return playSeconds, err
  483. }
  484. s = strings.Trim(s, " ")
  485. s = strings.Trim(s, "\n")
  486. sInt, err := strconv.ParseFloat(s, 64)
  487. if err != nil {
  488. return playSeconds, err
  489. }
  490. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  491. }
  492. return
  493. }
  494. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  495. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  496. tradeCode = strings.Trim(tradeCode, " ")
  497. tradeCodeInt, err := strconv.Atoi(tradeCode)
  498. if err != nil {
  499. return
  500. }
  501. tradeCodeInt = tradeCodeInt + 1
  502. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  503. return
  504. }
  505. // excel日期字段格式化 yyyy-mm-dd
  506. func ConvertToFormatDay(excelDaysString string) string {
  507. // 2006-01-02 距离 1900-01-01的天数
  508. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  509. curDiffDay := excelDaysString
  510. b, _ := strconv.Atoi(curDiffDay)
  511. // 获取excel的日期距离2006-01-02的天数
  512. realDiffDay := b - baseDiffDay
  513. //fmt.Println("realDiffDay:",realDiffDay)
  514. // 距离2006-01-02 秒数
  515. realDiffSecond := realDiffDay * 24 * 3600
  516. //fmt.Println("realDiffSecond:",realDiffSecond)
  517. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  518. baseOriginSecond := 1136185445
  519. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  520. return resultTime
  521. }
  522. func CheckPwd(pwd string) bool {
  523. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  524. reg := regexp.MustCompile(compile)
  525. flag := reg.MatchString(pwd)
  526. return flag
  527. }
  528. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  529. // 数字月份必须前置补零
  530. if len(myMonth) == 1 {
  531. myMonth = "0" + myMonth
  532. }
  533. yInt, _ := strconv.Atoi(myYear)
  534. timeLayout := "2006-01-02 15:04:05"
  535. loc, _ := time.LoadLocation("Local")
  536. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  537. newMonth := theTime.Month()
  538. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  539. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  540. return t1, t2
  541. }
  542. // 移除字符串中的空格
  543. func TrimStr(str string) (str2 string) {
  544. if str == "" {
  545. return str
  546. }
  547. return strings.Replace(str, " ", "", -1)
  548. }
  549. // 字符串转换为time
  550. func StrTimeToTime(strTime string) time.Time {
  551. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  552. loc, _ := time.LoadLocation("Local") //重要:获取时区
  553. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  554. return resultTime
  555. }
  556. // 字符串类型时间转周几
  557. func StrDateTimeToWeek(strTime string) string {
  558. var WeekDayMap = map[string]string{
  559. "Monday": "周一",
  560. "Tuesday": "周二",
  561. "Wednesday": "周三",
  562. "Thursday": "周四",
  563. "Friday": "周五",
  564. "Saturday": "周六",
  565. "Sunday": "周日",
  566. }
  567. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  568. startday, _ := time.ParseInLocation("2006-01-02", ctime, time.Local)
  569. staweek_int := startday.Weekday().String()
  570. return WeekDayMap[staweek_int]
  571. }
  572. // 时间格式转年月日字符串
  573. func TimeToStrYmd(time2 time.Time) string {
  574. var Ymd string
  575. year := time2.Year()
  576. month := time2.Format("1")
  577. day1 := time.Now().Day()
  578. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  579. return Ymd
  580. }
  581. // 时间格式去掉时分秒
  582. func TimeRemoveHms(strTime string) string {
  583. var Ymd string
  584. var resultTime = StrTimeToTime(strTime)
  585. year := resultTime.Year()
  586. month := resultTime.Format("01")
  587. day1 := resultTime.Day()
  588. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  589. return Ymd
  590. }
  591. // 时间格式去掉时分秒
  592. func TimeRemoveHms2(strTime string) string {
  593. var Ymd string
  594. var resultTime = StrTimeToTime(strTime)
  595. year := resultTime.Year()
  596. month := resultTime.Format("01")
  597. day1 := resultTime.Day()
  598. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  599. return Ymd
  600. }
  601. // 文章上一次编辑时间
  602. func ArticleLastTime(strTime string) string {
  603. var newTime string
  604. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  605. diffTime := time.Now().Unix() - stamp.Unix()
  606. if diffTime <= 60 {
  607. newTime = "当前"
  608. } else if diffTime < 60*60 {
  609. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  610. } else if diffTime < 24*60*60 {
  611. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  612. } else if diffTime < 30*24*60*60 {
  613. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  614. } else if diffTime < 12*30*24*60*60 {
  615. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  616. } else {
  617. newTime = "1年前"
  618. }
  619. return newTime
  620. }
  621. // 人民币小写转大写
  622. func ConvertNumToCny(num float64) (str string, err error) {
  623. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  624. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  625. // log.Println(sliceUnit[:len(sliceUnit)-2])
  626. s := sliceUnit[len(sliceUnit)-len(strNum):]
  627. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  628. for k, v := range strNum[:] {
  629. str = str + upperDigitUnit[string(v)] + s[k]
  630. }
  631. reg, err := regexp.Compile(`零角零分$`)
  632. str = reg.ReplaceAllString(str, "整")
  633. reg, err = regexp.Compile(`零角`)
  634. str = reg.ReplaceAllString(str, "零")
  635. reg, err = regexp.Compile(`零分$`)
  636. str = reg.ReplaceAllString(str, "整")
  637. reg, err = regexp.Compile(`零[仟佰拾]`)
  638. str = reg.ReplaceAllString(str, "零")
  639. reg, err = regexp.Compile(`零{2,}`)
  640. str = reg.ReplaceAllString(str, "零")
  641. reg, err = regexp.Compile(`零亿`)
  642. str = reg.ReplaceAllString(str, "亿")
  643. reg, err = regexp.Compile(`零万`)
  644. str = reg.ReplaceAllString(str, "万")
  645. reg, err = regexp.Compile(`零*元`)
  646. str = reg.ReplaceAllString(str, "元")
  647. reg, err = regexp.Compile(`亿零{0, 3}万`)
  648. str = reg.ReplaceAllString(str, "^元")
  649. reg, err = regexp.Compile(`零元`)
  650. str = reg.ReplaceAllString(str, "零")
  651. return
  652. }
  653. // GetNowWeekMonday 获取本周周一的时间
  654. func GetNowWeekMonday() time.Time {
  655. offset := int(time.Monday - time.Now().Weekday())
  656. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  657. offset = -6
  658. }
  659. mondayTime := time.Now().AddDate(0, 0, offset)
  660. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  661. return mondayTime
  662. }
  663. // GetNowWeekLastDay 获取本周最后一天的时间
  664. func GetNowWeekLastDay() time.Time {
  665. offset := int(time.Monday - time.Now().Weekday())
  666. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  667. offset = -6
  668. }
  669. firstDayTime := time.Now().AddDate(0, 0, offset)
  670. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  671. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  672. return lastDayTime
  673. }
  674. // GetNowMonthFirstDay 获取本月第一天的时间
  675. func GetNowMonthFirstDay() time.Time {
  676. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  677. return nowMonthFirstDay
  678. }
  679. // GetNowMonthLastDay 获取本月最后一天的时间
  680. func GetNowMonthLastDay() time.Time {
  681. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  682. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  683. return nowMonthLastDay
  684. }
  685. // GetNowQuarterFirstDay 获取本季度第一天的时间
  686. func GetNowQuarterFirstDay() time.Time {
  687. month := int(time.Now().Month())
  688. var nowQuarterFirstDay time.Time
  689. if month >= 1 && month <= 3 {
  690. //1月1号
  691. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  692. } else if month >= 4 && month <= 6 {
  693. //4月1号
  694. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  695. } else if month >= 7 && month <= 9 {
  696. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  697. } else {
  698. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  699. }
  700. return nowQuarterFirstDay
  701. }
  702. // GetNowQuarterLastDay 获取本季度最后一天的时间
  703. func GetNowQuarterLastDay() time.Time {
  704. month := int(time.Now().Month())
  705. var nowQuarterLastDay time.Time
  706. if month >= 1 && month <= 3 {
  707. //03-31 23:59:59
  708. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  709. } else if month >= 4 && month <= 6 {
  710. //06-30 23:59:59
  711. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  712. } else if month >= 7 && month <= 9 {
  713. //09-30 23:59:59
  714. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  715. } else {
  716. //12-31 23:59:59
  717. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  718. }
  719. return nowQuarterLastDay
  720. }
  721. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  722. func GetNowHalfYearFirstDay() time.Time {
  723. month := int(time.Now().Month())
  724. var nowHalfYearLastDay time.Time
  725. if month >= 1 && month <= 6 {
  726. //03-31 23:59:59
  727. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  728. } else {
  729. //12-31 23:59:59
  730. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  731. }
  732. return nowHalfYearLastDay
  733. }
  734. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  735. func GetNowHalfYearLastDay() time.Time {
  736. month := int(time.Now().Month())
  737. var nowHalfYearLastDay time.Time
  738. if month >= 1 && month <= 6 {
  739. //03-31 23:59:59
  740. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  741. } else {
  742. //12-31 23:59:59
  743. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  744. }
  745. return nowHalfYearLastDay
  746. }
  747. // GetNowYearFirstDay 获取当前年的最后一天的时间
  748. func GetNowYearFirstDay() time.Time {
  749. //12-31 23:59:59
  750. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  751. return nowYearFirstDay
  752. }
  753. // GetNowYearLastDay 获取当前年的最后一天的时间
  754. func GetNowYearLastDay() time.Time {
  755. //12-31 23:59:59
  756. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  757. return nowYearLastDay
  758. }
  759. // CalculationDate 计算两个日期之间相差n年m月y天
  760. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  761. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  762. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  763. numYear := endDate.Year() - startDate.Year()
  764. numMonth := int(endDate.Month()) - int(startDate.Month())
  765. numDay := 0
  766. //获取截止月的总天数
  767. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  768. //获取截止月的前一个月
  769. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  770. //获取截止日期的上一个月的总天数
  771. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  772. //获取开始日期的的月份总天数
  773. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  774. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  775. if endDate.Day() == endDateDays {
  776. numDay = startDateMonthDays - startDate.Day() + 1
  777. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  778. if numDay == startDateMonthDays {
  779. numMonth++
  780. numDay = 0
  781. //超过月份了,那么年份加1
  782. if numMonth == 12 {
  783. numYear++
  784. numMonth = 0
  785. }
  786. }
  787. } else {
  788. numDay = endDate.Day() - startDate.Day() + 1
  789. }
  790. //天数小于0,那么向月份借一位
  791. if numDay < 0 {
  792. //向上一个月借一个月的天数
  793. numDay += endDatePrevMonthDays
  794. //总月份减去一个月
  795. numMonth = numMonth - 1
  796. }
  797. //月份小于0,那么向年份借一位
  798. if numMonth < 0 {
  799. //向上一个年借12个月
  800. numMonth += 12
  801. //总年份减去一年
  802. numYear = numYear - 1
  803. }
  804. if numYear < 0 {
  805. err = errors.New("日期异常")
  806. return
  807. }
  808. if numYear > 0 {
  809. beetweenDay += fmt.Sprint(numYear, "年")
  810. }
  811. if numMonth > 0 {
  812. beetweenDay += fmt.Sprint(numMonth, "个月")
  813. }
  814. if numDay > 0 {
  815. beetweenDay += fmt.Sprint(numDay, "天")
  816. }
  817. return
  818. }
  819. // FormatPrice 格式化展示金额数字(财务金额展示,小数点前,每三位用,隔开) 1,234,567,898.55
  820. func FormatPrice(price float64) (str string) {
  821. str = decimal.NewFromFloat(price).String()
  822. length := len(str)
  823. if length < 4 {
  824. return str
  825. }
  826. arr := strings.Split(str, ".") //用小数点符号分割字符串,为数组接收
  827. length1 := len(arr[0])
  828. if length1 < 4 {
  829. return str
  830. }
  831. count := (length1 - 1) / 3
  832. for i := 0; i < count; i++ {
  833. arr[0] = arr[0][:length1-(i+1)*3] + "," + arr[0][length1-(i+1)*3:]
  834. }
  835. return strings.Join(arr, ".") //将一系列字符串连接为一个字符串,之间用sep来分隔。
  836. }
  837. // getMonthDay 获取某年某月有多少天
  838. func getMonthDay(year, month int) (days int) {
  839. if month != 2 {
  840. if month == 4 || month == 6 || month == 9 || month == 11 {
  841. days = 30
  842. } else {
  843. days = 31
  844. }
  845. } else {
  846. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  847. days = 29
  848. } else {
  849. days = 28
  850. }
  851. }
  852. return
  853. }
  854. func SaveToFile(content, path string) error {
  855. f, err := os.Create(path)
  856. defer f.Close()
  857. if err != nil {
  858. return err
  859. }
  860. f.Write([]byte(content))
  861. return nil
  862. }
  863. // HideString 给字段加***(从字符串中间替换,少于需要替换的长度,那么就补全*的长度)
  864. // src 待*字符串
  865. // hideLen 需要加*的长度
  866. func HideString(src string, hideLen int) string {
  867. if src == "" {
  868. return src
  869. }
  870. str := []rune(src)
  871. if hideLen == 0 {
  872. hideLen = 4
  873. }
  874. hideStr := ""
  875. for i := 0; i < hideLen; i++ {
  876. hideStr += "*"
  877. }
  878. strLen := len(str)
  879. // 字符长度是1
  880. if strLen == 1 {
  881. return string(str[:1]) + hideStr
  882. }
  883. //字符长度大于1,但是小于等于需要隐藏的字符长度,那么就隐藏中间,保留前后各一位字符
  884. if strLen <= hideLen+2 {
  885. return string(str[:1]) + hideStr + string(str[strLen-1:])
  886. }
  887. subLen := strLen - hideLen //剩余需要展示的字符长度
  888. decimal.NewFromFloat(2)
  889. frontLenDecimal := decimal.NewFromInt(int64(subLen)).Div(decimal.NewFromInt(2)) //前面需要展示的字符的长度
  890. frontLen := frontLenDecimal.Floor().IntPart()
  891. return string(str[:frontLen]) + hideStr + string(str[frontLen+int64(hideLen):])
  892. }
  893. // 用户参会时间转换
  894. func GetAttendanceDetailSeconds(secondNum int) string {
  895. var timeStr string
  896. if secondNum <= 60 {
  897. if secondNum < 10 {
  898. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  899. } else {
  900. timeStr = strconv.Itoa(secondNum) + "''"
  901. }
  902. } else {
  903. var remainderStr string
  904. remainderNum := secondNum % 60
  905. minuteNum := secondNum / 60
  906. if remainderNum < 10 {
  907. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  908. } else {
  909. remainderStr = strconv.Itoa(remainderNum) + "''"
  910. }
  911. if minuteNum < 10 {
  912. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  913. } else {
  914. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  915. }
  916. }
  917. return timeStr
  918. }
  919. // SubStr 截取字符串(中文)
  920. func SubStr(str string, subLen int) string {
  921. strRune := []rune(str)
  922. bodyRuneLen := len(strRune)
  923. if bodyRuneLen > subLen {
  924. bodyRuneLen = subLen
  925. }
  926. str = string(strRune[:bodyRuneLen])
  927. return str
  928. }
  929. func GetLocalIP() (ip string, err error) {
  930. addrs, err := net.InterfaceAddrs()
  931. if err != nil {
  932. return
  933. }
  934. for _, addr := range addrs {
  935. ipAddr, ok := addr.(*net.IPNet)
  936. if !ok {
  937. continue
  938. }
  939. if ipAddr.IP.IsLoopback() {
  940. continue
  941. }
  942. if !ipAddr.IP.IsGlobalUnicast() {
  943. continue
  944. }
  945. return ipAddr.IP.String(), nil
  946. }
  947. return
  948. }
  949. func PrintLog(params ...string) {
  950. _, file, line, ok := runtime.Caller(1)
  951. fmt.Println(file, line, ok, params)
  952. }
  953. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  954. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  955. for _, id := range idStrList {
  956. if id == searchId {
  957. has = true
  958. return
  959. }
  960. }
  961. return
  962. }
  963. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该Int值)
  964. func InArrayByInt(idStrList []int, searchId int) (has bool) {
  965. for _, id := range idStrList {
  966. if id == searchId {
  967. has = true
  968. return
  969. }
  970. }
  971. return
  972. }
  973. // GetOrmInReplace 获取orm的in查询替换?的方法
  974. func GetOrmInReplace(num int) string {
  975. template := make([]string, num)
  976. for i := 0; i < num; i++ {
  977. template[i] = "?"
  978. }
  979. return strings.Join(template, ",")
  980. }
  981. // GetTimeSubDay 计算两个时间的自然日期差
  982. func GetTimeSubDay(t1, t2 time.Time) int {
  983. var day int
  984. swap := false
  985. if t1.Unix() > t2.Unix() {
  986. t1, t2 = t2, t1
  987. swap = true
  988. }
  989. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  990. day = int(t2.Sub(t1).Hours() / 24)
  991. // 计算在t1+两个时间的余数之后天数是否有变化
  992. if t1_.Day() != t1.Day() {
  993. day += 1
  994. }
  995. if swap {
  996. day = -day
  997. }
  998. return day
  999. }
  1000. // GetFrequencyEndDay 根据当前时间和频度,获取该频度下最后一天的日期
  1001. func GetFrequencyEndDay(currDate time.Time, frequency string) (endDate time.Time) {
  1002. switch frequency {
  1003. case "周度":
  1004. // 如果当前就是最后一天,那么就直接返回本日期就好了
  1005. if currDate.Weekday() == 0 {
  1006. endDate = currDate
  1007. } else {
  1008. endDate = currDate.AddDate(0, 0, 7-int(currDate.Weekday()))
  1009. }
  1010. case "旬度":
  1011. nextDay := currDate.AddDate(0, 0, 1)
  1012. if nextDay.Day() == 1 || currDate.Day() == 10 || currDate.Day() == 20 {
  1013. //如果是每月10、20、最后一天,那么就直接返回本日期就好了
  1014. endDate = currDate
  1015. } else {
  1016. if currDate.Day() < 10 { // 每月10号
  1017. endDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, time.Local)
  1018. } else if currDate.Day() < 20 { // 每月10号
  1019. endDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, time.Local)
  1020. } else {
  1021. // 下旬,多种可能,最大天数可能存在8天,9天,10天,11天,
  1022. tmpNextMonth := currDate.AddDate(0, 0, 13)
  1023. endDate = time.Date(tmpNextMonth.Year(), tmpNextMonth.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  1024. }
  1025. }
  1026. case "月度":
  1027. nextDay := currDate.AddDate(0, 0, 1)
  1028. if nextDay.Day() == 1 {
  1029. //如果是每月的最后一天,那么就直接返回本日期就好了
  1030. endDate = currDate
  1031. } else {
  1032. endDate = time.Date(nextDay.Year(), nextDay.Month()+1, 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  1033. }
  1034. case "季度":
  1035. nextDay := currDate.AddDate(0, 0, 1)
  1036. if (nextDay.Month() == 1 || nextDay.Month() == 4 || nextDay.Month() == 7 || nextDay.Month() == 10) && nextDay.Day() == 1 {
  1037. //如果是每季的最后一天,那么就直接返回本日期就好了
  1038. endDate = currDate
  1039. } else {
  1040. if currDate.Month() < 4 { // 1季度
  1041. endDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, time.Local)
  1042. } else if currDate.Month() < 7 { // 2季度
  1043. endDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, time.Local)
  1044. } else if currDate.Month() < 10 { // 3季度
  1045. endDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, time.Local)
  1046. } else {
  1047. // 4季度
  1048. endDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  1049. }
  1050. }
  1051. case "年度":
  1052. endDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  1053. default:
  1054. endDate = currDate
  1055. return
  1056. }
  1057. return
  1058. }
  1059. // CheckFrequency 获取两个频度之间是否相对低高频
  1060. // 大于0,代表左侧是高频(例:左侧:日度,右侧:周度)
  1061. // 等于0,代表同频
  1062. // 小于0,代表右侧是高频(例:左侧:周度,右侧:日度)
  1063. func CheckFrequency(leftFrequency, rightFrequency string) int {
  1064. frequencyMap := map[string]int{
  1065. "年度": 0,
  1066. "半年度": 1,
  1067. "季度": 2,
  1068. "月度": 3,
  1069. "旬度": 4,
  1070. "周度": 5,
  1071. "日度": 6,
  1072. }
  1073. return frequencyMap[leftFrequency] - frequencyMap[rightFrequency]
  1074. }
  1075. // GetLikeKeyword
  1076. //
  1077. // @Description: 获取sql查询中的like查询字段
  1078. // @author: Roc
  1079. // @datetime2023-10-23 14:46:32
  1080. // @param keyword string
  1081. // @return string
  1082. func GetLikeKeyword(keyword string) string {
  1083. return `%` + keyword + `%`
  1084. }
  1085. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
  1086. startDate = tmpStartDate
  1087. endDate = tmpEndDate
  1088. switch dateType {
  1089. case 1:
  1090. startDate = "2000-01-01"
  1091. endDate = ""
  1092. case 2:
  1093. startDate = "2010-01-01"
  1094. endDate = ""
  1095. case 3:
  1096. startDate = "2015-01-01"
  1097. endDate = ""
  1098. case 4:
  1099. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1100. startDate = "2021-01-01"
  1101. endDate = ""
  1102. case 5:
  1103. //startDate = startDate + "-01"
  1104. //endDate = endDate + "-01"
  1105. case 6:
  1106. //startDate = startDate + "-01"
  1107. endDate = ""
  1108. case 7:
  1109. startDate = "2018-01-01"
  1110. endDate = ""
  1111. case 8:
  1112. startDate = "2019-01-01"
  1113. endDate = ""
  1114. case 9:
  1115. startDate = "2020-01-01"
  1116. endDate = ""
  1117. case 11:
  1118. startDate = "2022-01-01"
  1119. endDate = ""
  1120. case DateTypeNYears:
  1121. if startYear == 0 { //默认取最近5年
  1122. startYear = 5
  1123. }
  1124. if yearMax == 0 {
  1125. return
  1126. }
  1127. startYear = startYear - 1
  1128. baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
  1129. startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  1130. endDate = ""
  1131. }
  1132. // 兼容日期错误
  1133. {
  1134. if strings.Count(startDate, "-") == 1 {
  1135. startDate = startDate + "-01"
  1136. }
  1137. if strings.Count(endDate, "-") == 1 {
  1138. endDate = endDate + "-01"
  1139. }
  1140. }
  1141. return
  1142. }
  1143. // MapSorter 对于map 排序
  1144. type MapSorter []Item
  1145. type Item struct {
  1146. Key int
  1147. Val float64
  1148. }
  1149. func NewMapSorter(m map[int]float64) MapSorter {
  1150. ms := make(MapSorter, 0, len(m))
  1151. for k, v := range m {
  1152. ms = append(ms, Item{k, v})
  1153. }
  1154. return ms
  1155. }
  1156. func (ms MapSorter) Len() int {
  1157. return len(ms)
  1158. }
  1159. func (ms MapSorter) Less(i, j int) bool {
  1160. return ms[i].Val > ms[j].Val // 按值排序
  1161. //return ms[i].Key < ms[j].Key // 按键排序
  1162. }
  1163. func (ms MapSorter) Swap(i, j int) {
  1164. ms[i], ms[j] = ms[j], ms[i]
  1165. }
  1166. // GetDaysBetween2Date 计算两个日期之间相差几天
  1167. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  1168. // 将字符串转化为Time格式
  1169. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  1170. if err != nil {
  1171. return 0, err
  1172. }
  1173. // 将字符串转化为Time格式
  1174. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  1175. if err != nil {
  1176. return 0, err
  1177. }
  1178. //计算相差天数
  1179. return int(date1.Sub(date2).Hours() / 24), nil
  1180. }
  1181. func TimeTransferString(format string, t time.Time) string {
  1182. str := t.Format(format)
  1183. if t.IsZero() {
  1184. return ""
  1185. }
  1186. return str
  1187. }
  1188. // GetDiffDays 计算两个日期相差的天数
  1189. func GetDiffDays(t1, t2 time.Time) int {
  1190. t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
  1191. t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)
  1192. return int(t1.Sub(t2).Hours() / 24)
  1193. }
  1194. func GetDurationFormatBySecond(sec int) (formatString string) {
  1195. if sec == 0 {
  1196. formatString = "0分钟"
  1197. return
  1198. } else if sec <= 60 && sec > 0 {
  1199. formatString = "1分钟"
  1200. return
  1201. }
  1202. duration := time.Duration(int64(sec)) * time.Second
  1203. h := int(duration.Hours())
  1204. m := int(duration.Minutes()) % 60
  1205. //s := int(duration.Seconds()) % 60
  1206. if h > 0 {
  1207. formatString = fmt.Sprintf("%d小时", h)
  1208. }
  1209. if m > 0 {
  1210. formatString += fmt.Sprintf("%d分钟", m)
  1211. }
  1212. //if s > 0 {
  1213. // formatString += fmt.Sprintf("%d秒", s)
  1214. //}
  1215. return
  1216. }
  1217. // 去除非中文字符串
  1218. func StrFilterNonChinese(src *string) {
  1219. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$")
  1220. strn := ""
  1221. for _, c := range *src {
  1222. if hzRegexp.MatchString(string(c)) {
  1223. strn += string(c)
  1224. }
  1225. }
  1226. *src = strn
  1227. }
  1228. // GetFiccAdminDepartmentIds 获取ficc管理员的所属部门
  1229. func GetFiccAdminDepartmentIds() (idStr string) {
  1230. if RunMode == "release" {
  1231. idStr = `1,2,4,6`
  1232. } else {
  1233. idStr = `1,2,6`
  1234. }
  1235. return
  1236. }