common.go 33 KB

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