common.go 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977
  1. package utils
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/hmac"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "github.com/PuerkitoBio/goquery"
  14. "github.com/shopspring/decimal"
  15. "html"
  16. "image"
  17. "image/png"
  18. "io"
  19. "math"
  20. "math/rand"
  21. "net"
  22. "net/http"
  23. "os"
  24. "os/exec"
  25. "path"
  26. "regexp"
  27. "strconv"
  28. "strings"
  29. "time"
  30. )
  31. // 随机数种子
  32. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  33. func GetRandString(size int) string {
  34. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  35. randomSb := ""
  36. digitSize := len(allLetterDigit)
  37. for i := 0; i < size; i++ {
  38. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  39. }
  40. return randomSb
  41. }
  42. func GetRandStringNoSpecialChar(size int) string {
  43. 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"}
  44. randomSb := ""
  45. digitSize := len(allLetterDigit)
  46. for i := 0; i < size; i++ {
  47. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  48. }
  49. return randomSb
  50. }
  51. func StringsToJSON(str string) string {
  52. rs := []rune(str)
  53. jsons := ""
  54. for _, r := range rs {
  55. rint := int(r)
  56. if rint < 128 {
  57. jsons += string(r)
  58. } else {
  59. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  60. }
  61. }
  62. return jsons
  63. }
  64. // 序列化
  65. func ToString(v interface{}) string {
  66. data, _ := json.Marshal(v)
  67. return string(data)
  68. }
  69. // md5加密
  70. func MD5(data string) string {
  71. m := md5.Sum([]byte(data))
  72. return hex.EncodeToString(m[:])
  73. }
  74. // HmacMd5 HmacMd5加密
  75. func HmacMd5(key, data string) string {
  76. h := hmac.New(md5.New, []byte(key))
  77. h.Write([]byte(data))
  78. return hex.EncodeToString(h.Sum([]byte("")))
  79. }
  80. // 获取数字随机字符
  81. func GetRandDigit(n int) string {
  82. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  83. }
  84. // 获取随机数
  85. func GetRandNumber(n int) int {
  86. return rnd.Intn(n)
  87. }
  88. func GetRandInt(min, max int) int {
  89. if min >= max || min == 0 || max == 0 {
  90. return max
  91. }
  92. return rand.Intn(max-min) + min
  93. }
  94. func GetToday(format string) string {
  95. today := time.Now().Format(format)
  96. return today
  97. }
  98. // 获取今天剩余秒数
  99. func GetTodayLastSecond() time.Duration {
  100. today := GetToday(FormatDate) + " 23:59:59"
  101. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  102. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  103. }
  104. // 处理出生日期函数
  105. func GetBrithDate(idcard string) string {
  106. l := len(idcard)
  107. var s string
  108. if l == 15 {
  109. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  110. return s
  111. }
  112. if l == 18 {
  113. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  114. return s
  115. }
  116. return GetToday(FormatDate)
  117. }
  118. // 处理性别
  119. func WhichSexByIdcard(idcard string) string {
  120. var sexs = [2]string{"女", "男"}
  121. length := len(idcard)
  122. if length == 18 {
  123. sex, _ := strconv.Atoi(string(idcard[16]))
  124. return sexs[sex%2]
  125. } else if length == 15 {
  126. sex, _ := strconv.Atoi(string(idcard[14]))
  127. return sexs[sex%2]
  128. }
  129. return "男"
  130. }
  131. // 截取小数点后几位
  132. func SubFloatToString(f float64, m int) string {
  133. n := strconv.FormatFloat(f, 'f', -1, 64)
  134. if n == "" {
  135. return ""
  136. }
  137. if m >= len(n) {
  138. return n
  139. }
  140. newn := strings.Split(n, ".")
  141. if m == 0 {
  142. return newn[0]
  143. }
  144. if len(newn) < 2 || m >= len(newn[1]) {
  145. return n
  146. }
  147. return newn[0] + "." + newn[1][:m]
  148. }
  149. // 截取小数点后几位
  150. func SubFloatToFloat(f float64, m int) float64 {
  151. newn := SubFloatToString(f, m)
  152. newf, _ := strconv.ParseFloat(newn, 64)
  153. return newf
  154. }
  155. // 截取小数点后几位
  156. func SubFloatToFloatStr(f float64, m int) string {
  157. newn := SubFloatToString(f, m)
  158. return newn
  159. }
  160. // 获取相差时间-年
  161. func GetYearDiffer(start_time, end_time string) int {
  162. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  163. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  164. age := t2.Year() - t1.Year()
  165. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  166. age--
  167. }
  168. return age
  169. }
  170. // 获取相差时间-秒
  171. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  172. diff := end_time.Unix() - start_time.Unix()
  173. return diff
  174. }
  175. func FixFloat(f float64, m int) float64 {
  176. newn := SubFloatToString(f+0.00000001, m)
  177. newf, _ := strconv.ParseFloat(newn, 64)
  178. return newf
  179. }
  180. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  181. func StrListToString(strList []string) (str string) {
  182. if len(strList) > 0 {
  183. for k, v := range strList {
  184. if k == 0 {
  185. str = v
  186. } else {
  187. str = str + "," + v
  188. }
  189. }
  190. return
  191. }
  192. return ""
  193. }
  194. // Token
  195. func GetToken() string {
  196. randStr := GetRandString(64)
  197. token := MD5(randStr + Md5Key)
  198. tokenLen := 64 - len(token)
  199. return strings.ToUpper(token + GetRandString(tokenLen))
  200. }
  201. // 数据没有记录
  202. func ErrNoRow() string {
  203. return "<QuerySeter> no row found"
  204. }
  205. // 校验邮箱格式
  206. func ValidateEmailFormatat(email string) bool {
  207. reg := regexp.MustCompile(RegularEmail)
  208. return reg.MatchString(email)
  209. }
  210. // 验证是否是手机号
  211. func ValidateMobileFormatat(mobileNum string) bool {
  212. reg := regexp.MustCompile(RegularMobile)
  213. return reg.MatchString(mobileNum)
  214. }
  215. // 判断文件是否存在
  216. func FileIsExist(filePath string) bool {
  217. _, err := os.Stat(filePath)
  218. return err == nil || os.IsExist(err)
  219. }
  220. // 获取图片扩展名
  221. func GetImgExt(file string) (ext string, err error) {
  222. var headerByte []byte
  223. headerByte = make([]byte, 8)
  224. fd, err := os.Open(file)
  225. if err != nil {
  226. return "", err
  227. }
  228. defer fd.Close()
  229. _, err = fd.Read(headerByte)
  230. if err != nil {
  231. return "", err
  232. }
  233. xStr := fmt.Sprintf("%x", headerByte)
  234. switch {
  235. case xStr == "89504e470d0a1a0a":
  236. ext = ".png"
  237. case xStr == "0000010001002020":
  238. ext = ".ico"
  239. case xStr == "0000020001002020":
  240. ext = ".cur"
  241. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  242. ext = ".gif"
  243. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  244. ext = ".tga"
  245. case xStr[:8] == "464f524d":
  246. ext = ".iff"
  247. case xStr[:8] == "52494646":
  248. ext = ".ani"
  249. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  250. ext = ".tiff"
  251. case xStr[:4] == "424d":
  252. ext = ".bmp"
  253. case xStr[:4] == "ffd8":
  254. ext = ".jpg"
  255. case xStr[:2] == "0a":
  256. ext = ".pcx"
  257. default:
  258. ext = ""
  259. }
  260. return ext, nil
  261. }
  262. // 保存图片
  263. func SaveImage(path string, img image.Image) (err error) {
  264. //需要保持的文件
  265. imgfile, err := os.Create(path)
  266. defer imgfile.Close()
  267. // 以PNG格式保存文件
  268. err = png.Encode(imgfile, img)
  269. return err
  270. }
  271. // 下载图片
  272. func DownloadImage(imgUrl string) (filePath string, err error) {
  273. imgPath := "./static/imgs/"
  274. fileName := path.Base(imgUrl)
  275. res, err := http.Get(imgUrl)
  276. if err != nil {
  277. fmt.Println("A error occurred!")
  278. return
  279. }
  280. defer res.Body.Close()
  281. // 获得get请求响应的reader对象
  282. reader := bufio.NewReaderSize(res.Body, 32*1024)
  283. filePath = imgPath + fileName
  284. file, err := os.Create(filePath)
  285. if err != nil {
  286. return
  287. }
  288. // 获得文件的writer对象
  289. writer := bufio.NewWriter(file)
  290. written, _ := io.Copy(writer, reader)
  291. fmt.Printf("Total length: %d \n", written)
  292. return
  293. }
  294. // 保存base64数据为文件
  295. func SaveBase64ToFile(content, path string) error {
  296. data, err := base64.StdEncoding.DecodeString(content)
  297. if err != nil {
  298. return err
  299. }
  300. f, err := os.Create(path)
  301. defer f.Close()
  302. if err != nil {
  303. return err
  304. }
  305. f.Write(data)
  306. return nil
  307. }
  308. func SaveBase64ToFileBySeek(content, path string) (err error) {
  309. data, err := base64.StdEncoding.DecodeString(content)
  310. exist, err := PathExists(path)
  311. if err != nil {
  312. return
  313. }
  314. if !exist {
  315. f, err := os.Create(path)
  316. if err != nil {
  317. return err
  318. }
  319. n, _ := f.Seek(0, 2)
  320. // 从末尾的偏移量开始写入内容
  321. _, err = f.WriteAt([]byte(data), n)
  322. defer f.Close()
  323. } else {
  324. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  325. if err != nil {
  326. return err
  327. }
  328. n, _ := f.Seek(0, 2)
  329. // 从末尾的偏移量开始写入内容
  330. _, err = f.WriteAt([]byte(data), n)
  331. defer f.Close()
  332. }
  333. return nil
  334. }
  335. func PathExists(path string) (bool, error) {
  336. _, err := os.Stat(path)
  337. if err == nil {
  338. return true, nil
  339. }
  340. if os.IsNotExist(err) {
  341. return false, nil
  342. }
  343. return false, err
  344. }
  345. func StartIndex(page, pagesize int) int {
  346. if page > 1 {
  347. return (page - 1) * pagesize
  348. }
  349. return 0
  350. }
  351. func PageCount(count, pagesize int) int {
  352. if count%pagesize > 0 {
  353. return count/pagesize + 1
  354. } else {
  355. return count / pagesize
  356. }
  357. }
  358. func TrimHtml(src string) string {
  359. //将HTML标签全转换成小写
  360. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  361. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  362. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  363. src = re.ReplaceAllString(src, "")
  364. re, _ = regexp.Compile("class[\\S\\s]+?>")
  365. src = re.ReplaceAllString(src, "")
  366. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  367. src = re.ReplaceAllString(src, "")
  368. src = strings.ReplaceAll(src, "&nbsp;", " ")
  369. return strings.TrimSpace(src)
  370. }
  371. //1556164246 -> 2019-04-25 03:50:46 +0000
  372. //timestamp
  373. func TimeToTimestamp() {
  374. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  375. }
  376. func ToUnicode(text string) string {
  377. textQuoted := strconv.QuoteToASCII(text)
  378. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  379. return textUnquoted
  380. }
  381. func VersionToInt(version string) int {
  382. version = strings.Replace(version, ".", "", -1)
  383. n, _ := strconv.Atoi(version)
  384. return n
  385. }
  386. func IsCheckInList(list []int, s int) bool {
  387. for _, v := range list {
  388. if v == s {
  389. return true
  390. }
  391. }
  392. return false
  393. }
  394. func round(num float64) int {
  395. return int(num + math.Copysign(0.5, num))
  396. }
  397. func toFixed(num float64, precision int) float64 {
  398. output := math.Pow(10, float64(precision))
  399. return float64(round(num*output)) / output
  400. }
  401. // GetWilsonScore returns Wilson Score
  402. func GetWilsonScore(p, n float64) float64 {
  403. if p == 0 && n == 0 {
  404. return 0
  405. }
  406. 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)
  407. }
  408. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  409. func ChangeWordsToNum(str string) (numStr string) {
  410. words := ([]rune)(str)
  411. num := 0
  412. n := 0
  413. for i := 0; i < len(words); i++ {
  414. word := string(words[i : i+1])
  415. switch word {
  416. case "万":
  417. if n == 0 {
  418. n = 1
  419. }
  420. n = n * 10000
  421. num = num*10000 + n
  422. n = 0
  423. case "千":
  424. if n == 0 {
  425. n = 1
  426. }
  427. n = n * 1000
  428. num += n
  429. n = 0
  430. case "百":
  431. if n == 0 {
  432. n = 1
  433. }
  434. n = n * 100
  435. num += n
  436. n = 0
  437. case "十":
  438. if n == 0 {
  439. n = 1
  440. }
  441. n = n * 10
  442. num += n
  443. n = 0
  444. case "一":
  445. n += 1
  446. case "二":
  447. n += 2
  448. case "三":
  449. n += 3
  450. case "四":
  451. n += 4
  452. case "五":
  453. n += 5
  454. case "六":
  455. n += 6
  456. case "七":
  457. n += 7
  458. case "八":
  459. n += 8
  460. case "九":
  461. n += 9
  462. case "零":
  463. default:
  464. if n > 0 {
  465. num += n
  466. n = 0
  467. }
  468. if num == 0 {
  469. numStr += word
  470. } else {
  471. numStr += strconv.Itoa(num) + word
  472. num = 0
  473. }
  474. }
  475. }
  476. if n > 0 {
  477. num += n
  478. n = 0
  479. }
  480. if num != 0 {
  481. numStr += strconv.Itoa(num)
  482. }
  483. return
  484. }
  485. func Sha1(data string) string {
  486. sha1 := sha1.New()
  487. sha1.Write([]byte(data))
  488. return hex.EncodeToString(sha1.Sum([]byte("")))
  489. }
  490. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  491. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  492. out, err := exec.Command("bash", "-c", cmd).Output()
  493. if err != nil {
  494. return
  495. }
  496. outTimes := string(out)
  497. fmt.Println("outTimes:", outTimes)
  498. if outTimes != "" {
  499. timeArr := strings.Split(outTimes, ":")
  500. h := timeArr[0]
  501. m := timeArr[1]
  502. s := timeArr[2]
  503. hInt, err := strconv.Atoi(h)
  504. if err != nil {
  505. return playSeconds, err
  506. }
  507. mInt, err := strconv.Atoi(m)
  508. if err != nil {
  509. return playSeconds, err
  510. }
  511. s = strings.Trim(s, " ")
  512. s = strings.Trim(s, "\n")
  513. sInt, err := strconv.ParseFloat(s, 64)
  514. if err != nil {
  515. return playSeconds, err
  516. }
  517. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  518. }
  519. return
  520. }
  521. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  522. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  523. tradeCode = strings.Trim(tradeCode, " ")
  524. tradeCodeInt, err := strconv.Atoi(tradeCode)
  525. if err != nil {
  526. return
  527. }
  528. tradeCodeInt = tradeCodeInt + 1
  529. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  530. return
  531. }
  532. // excel日期字段格式化 yyyy-mm-dd
  533. func ConvertToFormatDay(excelDaysString string) string {
  534. // 2006-01-02 距离 1900-01-01的天数
  535. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  536. curDiffDay := excelDaysString
  537. b, _ := strconv.Atoi(curDiffDay)
  538. // 获取excel的日期距离2006-01-02的天数
  539. realDiffDay := b - baseDiffDay
  540. //fmt.Println("realDiffDay:",realDiffDay)
  541. // 距离2006-01-02 秒数
  542. realDiffSecond := realDiffDay * 24 * 3600
  543. //fmt.Println("realDiffSecond:",realDiffSecond)
  544. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  545. baseOriginSecond := 1136185445
  546. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  547. return resultTime
  548. }
  549. func CheckPwd(pwd string) bool {
  550. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  551. reg := regexp.MustCompile(compile)
  552. flag := reg.MatchString(pwd)
  553. return flag
  554. }
  555. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  556. // 数字月份必须前置补零
  557. if len(myMonth) == 1 {
  558. myMonth = "0" + myMonth
  559. }
  560. yInt, _ := strconv.Atoi(myYear)
  561. timeLayout := "2006-01-02 15:04:05"
  562. loc, _ := time.LoadLocation("Local")
  563. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  564. newMonth := theTime.Month()
  565. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  566. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  567. return t1, t2
  568. }
  569. // TrimStr 移除字符串中的空格
  570. func TrimStr(str string) (str2 string) {
  571. if str == "" {
  572. return str
  573. }
  574. return strings.Replace(str, " ", "", -1)
  575. }
  576. // TrimLRStr 移除字符串前后的空格
  577. func TrimLRStr(str string) (str2 string) {
  578. if str == "" {
  579. return str
  580. }
  581. str2 = strings.TrimLeft(str, " ")
  582. str2 = strings.TrimRight(str2, " ")
  583. return
  584. }
  585. // 字符串转换为time
  586. func StrTimeToTime(strTime string) time.Time {
  587. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  588. loc, _ := time.LoadLocation("Local") //重要:获取时区
  589. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  590. return resultTime
  591. }
  592. // 字符串类型时间转周几
  593. func StrDateTimeToWeek(strTime string) string {
  594. var WeekDayMap = map[string]string{
  595. "Monday": "周一",
  596. "Tuesday": "周二",
  597. "Wednesday": "周三",
  598. "Thursday": "周四",
  599. "Friday": "周五",
  600. "Saturday": "周六",
  601. "Sunday": "周日",
  602. }
  603. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  604. startday, _ := time.Parse("2006-01-02", ctime)
  605. staweek_int := startday.Weekday().String()
  606. return WeekDayMap[staweek_int]
  607. }
  608. // EnWeekToCnWeek 英文周几转中文周几
  609. func EnWeekToCnWeek(enWeekStr string) string {
  610. var WeekDayMap = map[string]string{
  611. "Monday": "周一",
  612. "Tuesday": "周二",
  613. "Wednesday": "周三",
  614. "Thursday": "周四",
  615. "Friday": "周五",
  616. "Saturday": "周六",
  617. "Sunday": "周日",
  618. }
  619. cnWeekStr, ok := WeekDayMap[enWeekStr]
  620. if !ok {
  621. cnWeekStr = `周一`
  622. }
  623. return cnWeekStr
  624. }
  625. // 时间格式转年月日字符串
  626. func TimeToStrYmd(time2 time.Time) string {
  627. var Ymd string
  628. year := time2.Year()
  629. month := time2.Format("1")
  630. day1 := time.Now().Day()
  631. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  632. return Ymd
  633. }
  634. // 时间格式去掉时分秒
  635. func TimeRemoveHms(strTime string) string {
  636. var Ymd string
  637. var resultTime = StrTimeToTime(strTime)
  638. year := resultTime.Year()
  639. month := resultTime.Format("01")
  640. day1 := resultTime.Day()
  641. if day1 < 10 {
  642. Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
  643. } else {
  644. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  645. }
  646. return Ymd
  647. }
  648. // 时间格式去掉时分秒
  649. func TimeRemoveHms2(strTime string) string {
  650. var Ymd string
  651. var resultTime = StrTimeToTime(strTime)
  652. year := resultTime.Year()
  653. month := resultTime.Format("01")
  654. day1 := resultTime.Day()
  655. if day1 < 10 {
  656. Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
  657. } else {
  658. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  659. }
  660. return Ymd
  661. }
  662. // 文章上一次编辑时间
  663. func ArticleLastTime(strTime string) string {
  664. var newTime string
  665. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  666. diffTime := time.Now().Unix() - stamp.Unix()
  667. if diffTime <= 60 {
  668. newTime = "当前"
  669. } else if diffTime < 60*60 {
  670. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  671. } else if diffTime < 24*60*60 {
  672. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  673. } else if diffTime < 30*24*60*60 {
  674. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  675. } else if diffTime < 12*30*24*60*60 {
  676. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  677. } else {
  678. newTime = "1年前"
  679. }
  680. return newTime
  681. }
  682. // 人民币小写转大写
  683. func ConvertNumToCny(num float64) (str string, err error) {
  684. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  685. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  686. // log.Println(sliceUnit[:len(sliceUnit)-2])
  687. s := sliceUnit[len(sliceUnit)-len(strNum):]
  688. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  689. for k, v := range strNum[:] {
  690. str = str + upperDigitUnit[string(v)] + s[k]
  691. }
  692. reg, err := regexp.Compile(`零角零分$`)
  693. str = reg.ReplaceAllString(str, "整")
  694. reg, err = regexp.Compile(`零角`)
  695. str = reg.ReplaceAllString(str, "零")
  696. reg, err = regexp.Compile(`零分$`)
  697. str = reg.ReplaceAllString(str, "整")
  698. reg, err = regexp.Compile(`零[仟佰拾]`)
  699. str = reg.ReplaceAllString(str, "零")
  700. reg, err = regexp.Compile(`零{2,}`)
  701. str = reg.ReplaceAllString(str, "零")
  702. reg, err = regexp.Compile(`零亿`)
  703. str = reg.ReplaceAllString(str, "亿")
  704. reg, err = regexp.Compile(`零万`)
  705. str = reg.ReplaceAllString(str, "万")
  706. reg, err = regexp.Compile(`零*元`)
  707. str = reg.ReplaceAllString(str, "元")
  708. reg, err = regexp.Compile(`亿零{0, 3}万`)
  709. str = reg.ReplaceAllString(str, "^元")
  710. reg, err = regexp.Compile(`零元`)
  711. str = reg.ReplaceAllString(str, "零")
  712. return
  713. }
  714. // GetNowWeekMonday 获取本周周一的时间
  715. func GetNowWeekMonday() time.Time {
  716. offset := int(time.Monday - time.Now().Weekday())
  717. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  718. offset = -6
  719. }
  720. mondayTime := time.Now().AddDate(0, 0, offset)
  721. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  722. return mondayTime
  723. }
  724. // GetNowWeekLastDay 获取本周最后一天的时间
  725. func GetNowWeekLastDay() time.Time {
  726. offset := int(time.Monday - time.Now().Weekday())
  727. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  728. offset = -6
  729. }
  730. firstDayTime := time.Now().AddDate(0, 0, offset)
  731. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  732. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  733. return lastDayTime
  734. }
  735. // GetNowMonthFirstDay 获取本月第一天的时间
  736. func GetNowMonthFirstDay() time.Time {
  737. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  738. return nowMonthFirstDay
  739. }
  740. // GetNowMonthLastDay 获取本月最后一天的时间
  741. func GetNowMonthLastDay() time.Time {
  742. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  743. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  744. return nowMonthLastDay
  745. }
  746. // GetNowQuarterFirstDay 获取本季度第一天的时间
  747. func GetNowQuarterFirstDay() time.Time {
  748. month := int(time.Now().Month())
  749. var nowQuarterFirstDay time.Time
  750. if month >= 1 && month <= 3 {
  751. //1月1号
  752. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  753. } else if month >= 4 && month <= 6 {
  754. //4月1号
  755. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  756. } else if month >= 7 && month <= 9 {
  757. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  758. } else {
  759. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  760. }
  761. return nowQuarterFirstDay
  762. }
  763. // GetNowQuarterLastDay 获取本季度最后一天的时间
  764. func GetNowQuarterLastDay() time.Time {
  765. month := int(time.Now().Month())
  766. var nowQuarterLastDay time.Time
  767. if month >= 1 && month <= 3 {
  768. //03-31 23:59:59
  769. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  770. } else if month >= 4 && month <= 6 {
  771. //06-30 23:59:59
  772. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  773. } else if month >= 7 && month <= 9 {
  774. //09-30 23:59:59
  775. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  776. } else {
  777. //12-31 23:59:59
  778. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  779. }
  780. return nowQuarterLastDay
  781. }
  782. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  783. func GetNowHalfYearFirstDay() time.Time {
  784. month := int(time.Now().Month())
  785. var nowHalfYearLastDay time.Time
  786. if month >= 1 && month <= 6 {
  787. //03-31 23:59:59
  788. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  789. } else {
  790. //12-31 23:59:59
  791. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  792. }
  793. return nowHalfYearLastDay
  794. }
  795. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  796. func GetNowHalfYearLastDay() time.Time {
  797. month := int(time.Now().Month())
  798. var nowHalfYearLastDay time.Time
  799. if month >= 1 && month <= 6 {
  800. //03-31 23:59:59
  801. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  802. } else {
  803. //12-31 23:59:59
  804. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  805. }
  806. return nowHalfYearLastDay
  807. }
  808. // GetNowYearFirstDay 获取当前年的最后一天的时间
  809. func GetNowYearFirstDay() time.Time {
  810. //12-31 23:59:59
  811. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  812. return nowYearFirstDay
  813. }
  814. // GetNowYearLastDay 获取当前年的最后一天的时间
  815. func GetNowYearLastDay() time.Time {
  816. //12-31 23:59:59
  817. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  818. return nowYearLastDay
  819. }
  820. // CalculationDate 计算两个日期之间相差n年m月y天
  821. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  822. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  823. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  824. numYear := endDate.Year() - startDate.Year()
  825. numMonth := int(endDate.Month()) - int(startDate.Month())
  826. numDay := 0
  827. //获取截止月的总天数
  828. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  829. //获取截止月的前一个月
  830. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  831. //获取截止日期的上一个月的总天数
  832. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  833. //获取开始日期的的月份总天数
  834. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  835. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  836. if endDate.Day() == endDateDays {
  837. numDay = startDateMonthDays - startDate.Day() + 1
  838. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  839. if numDay == startDateMonthDays {
  840. numMonth++
  841. numDay = 0
  842. //超过月份了,那么年份加1
  843. if numMonth == 12 {
  844. numYear++
  845. numMonth = 0
  846. }
  847. }
  848. } else {
  849. numDay = endDate.Day() - startDate.Day() + 1
  850. }
  851. //天数小于0,那么向月份借一位
  852. if numDay < 0 {
  853. //向上一个月借一个月的天数
  854. numDay += endDatePrevMonthDays
  855. //总月份减去一个月
  856. numMonth = numMonth - 1
  857. }
  858. //月份小于0,那么向年份借一位
  859. if numMonth < 0 {
  860. //向上一个年借12个月
  861. numMonth += 12
  862. //总年份减去一年
  863. numYear = numYear - 1
  864. }
  865. if numYear < 0 {
  866. err = errors.New("日期异常")
  867. return
  868. }
  869. if numYear > 0 {
  870. beetweenDay += fmt.Sprint(numYear, "年")
  871. }
  872. if numMonth > 0 {
  873. beetweenDay += fmt.Sprint(numMonth, "个月")
  874. }
  875. if numDay > 0 {
  876. beetweenDay += fmt.Sprint(numDay, "天")
  877. }
  878. return
  879. }
  880. // FormatPrice 格式化展示金额数字(财务金额展示,小数点前,每三位用,隔开) 1,234,567,898.55
  881. func FormatPrice(price float64) (str string) {
  882. str = decimal.NewFromFloat(price).String()
  883. length := len(str)
  884. if length < 4 {
  885. return str
  886. }
  887. arr := strings.Split(str, ".") //用小数点符号分割字符串,为数组接收
  888. length1 := len(arr[0])
  889. if length1 < 4 {
  890. return str
  891. }
  892. count := (length1 - 1) / 3
  893. for i := 0; i < count; i++ {
  894. arr[0] = arr[0][:length1-(i+1)*3] + "," + arr[0][length1-(i+1)*3:]
  895. }
  896. return strings.Join(arr, ".") //将一系列字符串连接为一个字符串,之间用sep来分隔。
  897. }
  898. // getMonthDay 获取某年某月有多少天
  899. func getMonthDay(year, month int) (days int) {
  900. if month != 2 {
  901. if month == 4 || month == 6 || month == 9 || month == 11 {
  902. days = 30
  903. } else {
  904. days = 31
  905. }
  906. } else {
  907. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  908. days = 29
  909. } else {
  910. days = 28
  911. }
  912. }
  913. return
  914. }
  915. func SaveToFile(content, path string) error {
  916. f, err := os.Create(path)
  917. defer f.Close()
  918. if err != nil {
  919. return err
  920. }
  921. f.Write([]byte(content))
  922. return nil
  923. }
  924. // 用户参会时间转换
  925. func GetAttendanceDetailSeconds(secondNum int) string {
  926. var timeStr string
  927. if secondNum <= 60 {
  928. if secondNum < 10 {
  929. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  930. } else {
  931. timeStr = strconv.Itoa(secondNum) + "''"
  932. }
  933. } else {
  934. var remainderStr string
  935. remainderNum := secondNum % 60
  936. minuteNum := secondNum / 60
  937. if remainderNum < 10 {
  938. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  939. } else {
  940. remainderStr = strconv.Itoa(remainderNum) + "''"
  941. }
  942. if minuteNum < 10 {
  943. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  944. } else {
  945. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  946. }
  947. }
  948. return timeStr
  949. }
  950. // SubStr 截取字符串(中文)
  951. func SubStr(str string, subLen int) string {
  952. strRune := []rune(str)
  953. bodyRuneLen := len(strRune)
  954. if bodyRuneLen > subLen {
  955. bodyRuneLen = subLen
  956. }
  957. str = string(strRune[:bodyRuneLen])
  958. return str
  959. }
  960. // HideString 给字段加***(从字符串中间替换,少于需要替换的长度,那么就补全*的长度)
  961. // src 待*字符串
  962. // hideLen 需要加*的长度
  963. func HideString(src string, hideLen int) string {
  964. if src == "" {
  965. return src
  966. }
  967. str := []rune(src)
  968. if hideLen == 0 {
  969. hideLen = 4
  970. }
  971. hideStr := ""
  972. for i := 0; i < hideLen; i++ {
  973. hideStr += "*"
  974. }
  975. strLen := len(str)
  976. // 字符长度是1
  977. if strLen == 1 {
  978. return string(str[:1]) + hideStr
  979. }
  980. //字符长度大于1,但是小于等于需要隐藏的字符长度,那么就隐藏中间,保留前后各一位字符
  981. if strLen <= hideLen+2 {
  982. return string(str[:1]) + hideStr + string(str[strLen-1:])
  983. }
  984. subLen := strLen - hideLen //剩余需要展示的字符长度
  985. decimal.NewFromFloat(2)
  986. frontLenDecimal := decimal.NewFromInt(int64(subLen)).Div(decimal.NewFromInt(2)) //前面需要展示的字符的长度
  987. frontLen := frontLenDecimal.Floor().IntPart()
  988. return string(str[:frontLen]) + hideStr + string(str[frontLen+int64(hideLen):])
  989. }
  990. func GetLocalIP() (ip string, err error) {
  991. addrs, err := net.InterfaceAddrs()
  992. if err != nil {
  993. return
  994. }
  995. for _, addr := range addrs {
  996. ipAddr, ok := addr.(*net.IPNet)
  997. if !ok {
  998. continue
  999. }
  1000. if ipAddr.IP.IsLoopback() {
  1001. continue
  1002. }
  1003. if !ipAddr.IP.IsGlobalUnicast() {
  1004. continue
  1005. }
  1006. return ipAddr.IP.String(), nil
  1007. }
  1008. return
  1009. }
  1010. // GetNowWeekMonday 获取上一周周一的时间
  1011. func GetPreWeekMonday() time.Time {
  1012. nowMonday := GetNowWeekMonday()
  1013. return nowMonday.AddDate(0, 0, -7)
  1014. }
  1015. // GetNowWeekLastDay 获取上一周最后一天的时间
  1016. func GetPreWeekLastDay() time.Time {
  1017. nowSunday := GetNowWeekLastDay()
  1018. return nowSunday.AddDate(0, 0, -7)
  1019. }
  1020. // GetNextWeekMonday 获取下一周周一的时间
  1021. func GetNextWeekMonday() time.Time {
  1022. nowMonday := GetNowWeekMonday()
  1023. return nowMonday.AddDate(0, 0, 7)
  1024. }
  1025. // GetNextWeekLastDay 获取下一周最后一天的时间
  1026. func GetNextWeekLastDay() time.Time {
  1027. nowSunday := GetNowWeekLastDay()
  1028. return nowSunday.AddDate(0, 0, 7)
  1029. }
  1030. // 处理真实姓名,隐藏中间的部分,如:张*,张*将
  1031. func DealRealName(realName string) string {
  1032. if realName == "" {
  1033. return ""
  1034. }
  1035. names := bytes.Runes([]byte(realName))
  1036. fistName := names[0]
  1037. length := len(names)
  1038. if length == 2 {
  1039. return string(fistName) + "*"
  1040. } else if length > 2 {
  1041. lastName := names[length-1]
  1042. return string(fistName) + "*" + string(lastName)
  1043. }
  1044. return realName
  1045. }
  1046. // Implode php中的implode(用来将int型的切片转为string)
  1047. func Implode(idIntList []int) (str string) {
  1048. for _, id := range idIntList {
  1049. str += fmt.Sprint(id, ",")
  1050. }
  1051. str = str[:len(str)-1]
  1052. return
  1053. }
  1054. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  1055. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  1056. for _, id := range idIntList {
  1057. if id == searchId {
  1058. has = true
  1059. return
  1060. }
  1061. }
  1062. return
  1063. }
  1064. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  1065. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  1066. for _, id := range idStrList {
  1067. if id == searchId {
  1068. has = true
  1069. return
  1070. }
  1071. }
  1072. return
  1073. }
  1074. // Intersection 求两个切片的交集
  1075. func Intersection(a []string, b []string) (inter []string) {
  1076. // interacting on the smallest list first can potentailly be faster...but not by much, worse case is the same
  1077. low, high := a, b
  1078. if len(a) > len(b) {
  1079. low = b
  1080. high = a
  1081. }
  1082. done := false
  1083. for i, l := range low {
  1084. for j, h := range high {
  1085. // get future index values
  1086. f1 := i + 1
  1087. f2 := j + 1
  1088. if l == h {
  1089. inter = append(inter, h)
  1090. if f1 < len(low) && f2 < len(high) {
  1091. // if the future values aren't the same then that's the end of the intersection
  1092. if low[f1] != high[f2] {
  1093. done = true
  1094. }
  1095. }
  1096. // we don't want to interate on the entire list everytime, so remove the parts we already looped on will make it faster each pass
  1097. high = high[:j+copy(high[j:], high[j+1:])]
  1098. break
  1099. }
  1100. }
  1101. // nothing in the future so we are done
  1102. if done {
  1103. break
  1104. }
  1105. }
  1106. return
  1107. }
  1108. // Minus 获取差集
  1109. func Minus(a []string, b []string) []string {
  1110. //var inter []string
  1111. inter := make([]string, 0)
  1112. mp := make(map[string]bool)
  1113. for _, s := range a {
  1114. if _, ok := mp[s]; !ok {
  1115. mp[s] = true
  1116. }
  1117. }
  1118. for _, s := range b {
  1119. if _, ok := mp[s]; ok {
  1120. delete(mp, s)
  1121. }
  1122. }
  1123. for key := range mp {
  1124. inter = append(inter, key)
  1125. }
  1126. return inter
  1127. }
  1128. // IntArr2joinString []int转字符串
  1129. func IntArr2joinString(arr []int, sep string) string {
  1130. if len(arr) == 0 {
  1131. return ""
  1132. }
  1133. strArr := make([]string, 0)
  1134. for _, v := range arr {
  1135. strArr = append(strArr, strconv.Itoa(v))
  1136. }
  1137. return strings.Join(strArr, sep)
  1138. }
  1139. // GetOneMonthFirstDay 获取某月的第一天的时间
  1140. func GetOneMonthFirstDay(time2 time.Time) time.Time {
  1141. nowMonthFirstDay := time.Date(time2.Year(), time2.Month(), 1, 0, 0, 0, 0, time.Now().Location())
  1142. return nowMonthFirstDay
  1143. }
  1144. // GetOneMonthLastDay 获取某月最后一天的时间
  1145. func GetOneMonthLastDay(time2 time.Time) time.Time {
  1146. nowMonthLastDay := time.Date(time2.Year(), time2.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1147. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  1148. return nowMonthLastDay
  1149. }
  1150. func GetReportContentTextSub(content string) (contentSub string, err error) {
  1151. content = html.UnescapeString(content)
  1152. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  1153. docText := doc.Text()
  1154. bodyRune := []rune(docText)
  1155. bodyRuneLen := len(bodyRune)
  1156. if bodyRuneLen > 200 {
  1157. bodyRuneLen = 200
  1158. }
  1159. body := string(bodyRune[:bodyRuneLen])
  1160. contentSub = body
  1161. contentSub = strings.Replace(body, "Powered by Froala Editor", "", -1)
  1162. return
  1163. }
  1164. // GetOrmInReplace 获取orm的in查询替换?的方法
  1165. func GetOrmInReplace(num int) string {
  1166. template := make([]string, num)
  1167. for i := 0; i < num; i++ {
  1168. template[i] = "?"
  1169. }
  1170. return strings.Join(template, ",")
  1171. }
  1172. // RevSlice 反转切片
  1173. func RevSlice(slice []int) []int {
  1174. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  1175. slice[i], slice[j] = slice[j], slice[i]
  1176. }
  1177. return slice
  1178. }
  1179. // ReplaceSpaceAndWrap 去除空格跟换行
  1180. func ReplaceSpaceAndWrap(str string) string {
  1181. // 去除空格
  1182. str = strings.Replace(str, " ", "", -1)
  1183. // 去除换行符
  1184. str = strings.Replace(str, "\n", "", -1)
  1185. return str
  1186. }
  1187. // JoinStr2IntArr 拼接字符串转[]int
  1188. func JoinStr2IntArr(str, sep string) (arr []int) {
  1189. arr = make([]int, 0)
  1190. if str == "" {
  1191. return
  1192. }
  1193. if sep == "" {
  1194. sep = ","
  1195. }
  1196. strArr := strings.Split(str, sep)
  1197. if len(strArr) == 0 {
  1198. return
  1199. }
  1200. for i := range strArr {
  1201. v, e := strconv.Atoi(strArr[i])
  1202. // int2str此处过滤掉无效int
  1203. if e != nil {
  1204. continue
  1205. }
  1206. arr = append(arr, v)
  1207. }
  1208. return
  1209. }
  1210. // 字符串转换为time类型
  1211. func StrDateToDate(strTime string) time.Time {
  1212. timeLayout := "2006-01-02" //转化所需模板
  1213. loc, _ := time.LoadLocation("Local") //重要:获取时区
  1214. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  1215. return resultTime
  1216. }
  1217. // GetTimeSubDay 计算两个时间的自然日期差(后面减去前面)
  1218. func GetTimeSubDay(t1, t2 time.Time) int {
  1219. var day int
  1220. swap := false
  1221. if t1.Unix() > t2.Unix() {
  1222. t1, t2 = t2, t1
  1223. swap = true
  1224. }
  1225. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  1226. day = int(t2.Sub(t1).Hours() / 24)
  1227. // 计算在t1+两个时间的余数之后天数是否有变化
  1228. if t1_.Day() != t1.Day() {
  1229. day += 1
  1230. }
  1231. if swap {
  1232. day = -day
  1233. }
  1234. return day
  1235. }
  1236. // 去除非中文字符串
  1237. func StrFilterNonChinese(src *string) {
  1238. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$")
  1239. strn := ""
  1240. for _, c := range *src {
  1241. if hzRegexp.MatchString(string(c)) {
  1242. strn += string(c)
  1243. }
  1244. }
  1245. *src = strn
  1246. }
  1247. // MinusInt 获取两个[]int差集
  1248. func MinusInt(a []int, b []int) []int {
  1249. var diff []int
  1250. mpA, mpB := make(map[int]bool), make(map[int]bool)
  1251. for _, v := range a {
  1252. mpA[v] = true
  1253. }
  1254. for _, v := range b {
  1255. mpB[v] = true
  1256. }
  1257. for _, s := range a {
  1258. if !mpB[s] {
  1259. diff = append(diff, s)
  1260. }
  1261. }
  1262. for _, s := range b {
  1263. if !mpA[s] {
  1264. diff = append(diff, s)
  1265. }
  1266. }
  1267. return diff
  1268. }
  1269. // IntersectInt 获取两个[]int交集
  1270. func IntersectInt(nums1 []int, nums2 []int) []int {
  1271. m := make(map[int]int)
  1272. var res []int
  1273. for _, num := range nums1 {
  1274. m[num]++
  1275. }
  1276. for _, num := range nums2 {
  1277. if m[num] > 0 {
  1278. res = append(res, num)
  1279. m[num]--
  1280. }
  1281. }
  1282. return res
  1283. }
  1284. // MapSorter 对于map 排序
  1285. type MapSorter []Item
  1286. type Item struct {
  1287. Key int
  1288. Val float64
  1289. }
  1290. func NewMapSorter(m map[int]float64) MapSorter {
  1291. ms := make(MapSorter, 0, len(m))
  1292. for k, v := range m {
  1293. ms = append(ms, Item{k, v})
  1294. }
  1295. return ms
  1296. }
  1297. func (ms MapSorter) Len() int {
  1298. return len(ms)
  1299. }
  1300. func (ms MapSorter) Less(i, j int) bool {
  1301. return ms[i].Val > ms[j].Val // 按值排序
  1302. //return ms[i].Key < ms[j].Key // 按键排序
  1303. }
  1304. func (ms MapSorter) Swap(i, j int) {
  1305. ms[i], ms[j] = ms[j], ms[i]
  1306. }
  1307. // FormatFileSize 字节的单位转换 保留两位小数
  1308. func FormatFileSize(fileSize int64) (size string) {
  1309. if fileSize < 1024 {
  1310. return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
  1311. } else if fileSize < (1024 * 1024) {
  1312. return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
  1313. } else if fileSize < (1024 * 1024 * 1024) {
  1314. return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
  1315. } else if fileSize < (1024 * 1024 * 1024 * 1024) {
  1316. return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
  1317. } else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
  1318. return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
  1319. } else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
  1320. return fmt.Sprintf("%.2fPB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
  1321. }
  1322. }
  1323. func GetDurationFormatBySecond(sec int) (formatString string) {
  1324. if sec == 0 {
  1325. formatString = "0分钟"
  1326. return
  1327. } else if sec <= 60 && sec > 0 {
  1328. formatString = "1分钟"
  1329. return
  1330. }
  1331. duration := time.Duration(int64(sec)) * time.Second
  1332. h := int(duration.Hours())
  1333. m := int(duration.Minutes()) % 60
  1334. //s := int(duration.Seconds()) % 60
  1335. if h > 0 {
  1336. formatString = fmt.Sprintf("%d小时", h)
  1337. }
  1338. if m > 0 {
  1339. formatString += fmt.Sprintf("%d分钟", m)
  1340. }
  1341. //if s > 0 {
  1342. // formatString += fmt.Sprintf("%d秒", s)
  1343. //}
  1344. return
  1345. }
  1346. // GetDaysBetween2Date 计算两个日期之间相差几天
  1347. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  1348. // 将字符串转化为Time格式
  1349. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  1350. if err != nil {
  1351. return 0, err
  1352. }
  1353. // 将字符串转化为Time格式
  1354. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  1355. if err != nil {
  1356. return 0, err
  1357. }
  1358. //计算相差天数
  1359. return int(date1.Sub(date2).Hours() / 24), nil
  1360. }
  1361. // GetFrequencyEn 获取频度的英文版
  1362. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1363. switch frequency {
  1364. case "日度":
  1365. frequencyEn = "day"
  1366. return
  1367. case "周度":
  1368. frequencyEn = "week"
  1369. return
  1370. case "旬度":
  1371. frequencyEn = "ten days"
  1372. return
  1373. case "月度":
  1374. frequencyEn = "month"
  1375. return
  1376. case "季度":
  1377. frequencyEn = "quarter"
  1378. return
  1379. case "年度":
  1380. frequencyEn = "year"
  1381. return
  1382. }
  1383. return
  1384. }
  1385. // GetLeadUnitEn 获取移动单位的英文版
  1386. func GetLeadUnitEn(unit string) (unitEn string) {
  1387. switch unit {
  1388. case "天":
  1389. unitEn = "day"
  1390. return
  1391. case "周":
  1392. unitEn = "week"
  1393. return
  1394. case "月":
  1395. unitEn = "month"
  1396. return
  1397. case "季":
  1398. unitEn = "quarter"
  1399. return
  1400. case "年":
  1401. unitEn = "year"
  1402. return
  1403. }
  1404. return
  1405. }
  1406. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  1407. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  1408. startDate = tmpStartDate
  1409. endDate = tmpEndDate
  1410. switch dateType {
  1411. case 1:
  1412. startDate = "2000-01-01"
  1413. endDate = ""
  1414. case 2:
  1415. startDate = "2010-01-01"
  1416. endDate = ""
  1417. case 3:
  1418. startDate = "2015-01-01"
  1419. endDate = ""
  1420. case 4:
  1421. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1422. startDate = "2021-01-01"
  1423. endDate = ""
  1424. case 5:
  1425. //startDate = startDate + "-01"
  1426. //endDate = endDate + "-01"
  1427. case 6:
  1428. //startDate = startDate + "-01"
  1429. endDate = ""
  1430. case 7:
  1431. startDate = "2018-01-01"
  1432. endDate = ""
  1433. case 8:
  1434. startDate = "2019-01-01"
  1435. endDate = ""
  1436. case 9:
  1437. startDate = "2020-01-01"
  1438. endDate = ""
  1439. case 11:
  1440. startDate = "2022-01-01"
  1441. endDate = ""
  1442. }
  1443. // 兼容日期错误
  1444. {
  1445. if strings.Count(startDate, "-") == 1 {
  1446. startDate = startDate + "-01"
  1447. }
  1448. if strings.Count(endDate, "-") == 1 {
  1449. endDate = endDate + "-01"
  1450. }
  1451. }
  1452. return
  1453. }
  1454. func TimeTransferString(format string, t time.Time) string {
  1455. str := t.Format(format)
  1456. if t.IsZero() {
  1457. return ""
  1458. }
  1459. return str
  1460. }
  1461. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  1462. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  1463. switch dateType {
  1464. case 1:
  1465. startDate = currDate.AddDate(0, -3, 0)
  1466. case 2:
  1467. startDate = currDate.AddDate(0, -6, 0)
  1468. case 3:
  1469. startDate = currDate.AddDate(-1, 0, 0)
  1470. case 4:
  1471. startDate = currDate.AddDate(-2, 0, 0)
  1472. case 5:
  1473. startDate = currDate.AddDate(-3, 0, 0)
  1474. case 6:
  1475. startDate = currDate.AddDate(-5, 0, 0)
  1476. case 7:
  1477. startDate = currDate.AddDate(-10, 0, 0)
  1478. }
  1479. return
  1480. }
  1481. // GetCeilNewNum 保留n位有效数字的向上取整
  1482. // @params num 实际数据
  1483. // @params baseLen 需要保留的有效位数
  1484. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  1485. if num >= 1 {
  1486. tmpNum := int(math.Ceil(num)) // 向上取整
  1487. str := strconv.Itoa(tmpNum)
  1488. lenStr := len(str)
  1489. if lenStr > baseLen {
  1490. newNumStr := str[0:baseLen]
  1491. newNumInt, _ := strconv.Atoi(newNumStr)
  1492. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1493. if newNum < num {
  1494. newNumInt += 1
  1495. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1496. }
  1497. } else {
  1498. newNum = float64(tmpNum)
  1499. }
  1500. return
  1501. } else if num > 0 {
  1502. // 这是小数
  1503. str := strconv.FormatFloat(num, 'f', -1, 64)
  1504. // 去除小数点和负号
  1505. str = removeDecimalPoint(str)
  1506. // 计算字符串长度
  1507. lenStr := len(str)
  1508. if lenStr > baseLen {
  1509. newNumStr := str[0:baseLen]
  1510. newNumInt, _ := strconv.Atoi(newNumStr)
  1511. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1512. if newNum < num {
  1513. newNumInt += 1
  1514. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1515. }
  1516. } else {
  1517. newNum = num
  1518. }
  1519. } else if num > -1 {
  1520. // 这是小数
  1521. str := strconv.FormatFloat(num, 'f', -1, 64)
  1522. // 去除小数点和负号
  1523. str = removeDecimalPoint(str)
  1524. // 计算字符串长度
  1525. lenStr := len(str)
  1526. if lenStr > baseLen {
  1527. newNumStr := str[0:baseLen]
  1528. newNumInt, _ := strconv.Atoi(newNumStr)
  1529. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1530. newNum = -newNum
  1531. if newNum < num {
  1532. newNumInt -= 1
  1533. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1534. newNum = -newNum
  1535. }
  1536. } else {
  1537. newNum = num
  1538. }
  1539. if newNum == -0 {
  1540. newNum = 0
  1541. }
  1542. } else { // 小于等于-1
  1543. tmpNumFloat := math.Abs(num)
  1544. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  1545. str := strconv.Itoa(tmpNum)
  1546. lenStr := len(str)
  1547. if lenStr > baseLen {
  1548. newNumStr := str[0:baseLen]
  1549. //fmt.Println("newNumStr:", newNumStr)
  1550. newNumInt, _ := strconv.Atoi(newNumStr)
  1551. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1552. newNum = -newNum
  1553. if newNum < num {
  1554. newNumInt -= 1
  1555. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1556. newNum = -newNum
  1557. }
  1558. } else {
  1559. newNum = float64(-tmpNum)
  1560. }
  1561. }
  1562. return
  1563. }
  1564. // GetFloorNewNum 保留n位有效数字的向下取整
  1565. // @params num 实际数据
  1566. // @params baseLen 需要保留的有效位数
  1567. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  1568. if num >= 1 {
  1569. tmpNum := int(math.Floor(num)) // 向上取整
  1570. str := strconv.Itoa(tmpNum)
  1571. lenStr := len(str)
  1572. if lenStr > baseLen {
  1573. newNumStr := str[0:baseLen]
  1574. newNumInt, _ := strconv.Atoi(newNumStr)
  1575. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1576. if newNum < num {
  1577. newNumInt -= 1
  1578. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1579. }
  1580. } else {
  1581. newNum = float64(tmpNum)
  1582. }
  1583. return
  1584. } else if num > 0 {
  1585. // 这是小数
  1586. str := strconv.FormatFloat(num, 'f', -1, 64)
  1587. // 去除小数点和负号
  1588. str = removeDecimalPoint(str)
  1589. // 计算字符串长度
  1590. lenStr := len(str)
  1591. if lenStr > baseLen {
  1592. newNumStr := str[0:baseLen]
  1593. newNumInt, _ := strconv.Atoi(newNumStr)
  1594. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1595. if newNum > num {
  1596. newNumInt -= 1
  1597. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1598. }
  1599. } else {
  1600. newNum = num
  1601. }
  1602. } else if num > -1 {
  1603. // 这是小数
  1604. str := strconv.FormatFloat(num, 'f', -1, 64)
  1605. // 去除小数点和负号
  1606. str = removeDecimalPoint(str)
  1607. // 计算字符串长度
  1608. lenStr := len(str)
  1609. if lenStr > baseLen {
  1610. newNumStr := str[0:baseLen]
  1611. newNumInt, _ := strconv.Atoi(newNumStr)
  1612. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1613. newNum = -newNum
  1614. if newNum > num {
  1615. newNumInt += 1
  1616. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1617. newNum = -newNum
  1618. }
  1619. } else {
  1620. newNum = num
  1621. }
  1622. if newNum == -0 {
  1623. newNum = 0
  1624. }
  1625. } else { // 小于等于-1
  1626. tmpNumFloat := math.Abs(num)
  1627. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  1628. str := strconv.Itoa(tmpNum)
  1629. lenStr := len(str)
  1630. if lenStr > baseLen {
  1631. newNumStr := str[0:baseLen]
  1632. //fmt.Println("newNumStr:", newNumStr)
  1633. newNumInt, _ := strconv.Atoi(newNumStr)
  1634. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1635. newNum = -newNum
  1636. if newNum > num {
  1637. newNumInt += 1
  1638. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1639. newNum = -newNum
  1640. }
  1641. } else {
  1642. newNum = float64(-tmpNum)
  1643. }
  1644. }
  1645. return
  1646. }
  1647. // 去除小数点和负号
  1648. func removeDecimalPoint(str string) string {
  1649. // 去除小数点
  1650. str = str[strings.Index(str, ".")+1:]
  1651. return str
  1652. }
  1653. // GetPredictEdbDayListByEndDate 根据截止日期获取预测指标日期列表
  1654. func GetPredictEdbDayListByEndDate(startDate, endDate time.Time, frequency string) (dayList []time.Time) {
  1655. //if !utils.InArrayByStr([]string{"日度", "周度", "月度"}, frequency)
  1656. switch frequency {
  1657. case "日度":
  1658. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 1) {
  1659. //周六、日排除
  1660. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1661. continue
  1662. }
  1663. dayList = append(dayList, currDate)
  1664. }
  1665. case "周度":
  1666. //nextDate := startDate.AddDate(0, 0, 7)
  1667. for currDate := startDate.AddDate(0, 0, 7); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 7) {
  1668. dayList = append(dayList, currDate)
  1669. }
  1670. case "旬度":
  1671. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); {
  1672. nextDate := currDate.AddDate(0, 0, 1)
  1673. //每个月的10号、20号、最后一天,那么就写入
  1674. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1675. dayList = append(dayList, currDate)
  1676. }
  1677. currDate = nextDate
  1678. }
  1679. case "月度":
  1680. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1681. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1682. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1683. dayList = append(dayList, currDate)
  1684. }
  1685. currDate = currDate.AddDate(0, 0, 1)
  1686. }
  1687. case "季度":
  1688. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1689. // 每月的最后一天
  1690. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1691. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1692. // 季度日期就写入,否则不写入
  1693. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1694. dayList = append(dayList, currDate)
  1695. }
  1696. }
  1697. currDate = currDate.AddDate(0, 0, 1)
  1698. }
  1699. case "半年度":
  1700. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1701. // 每月的最后一天
  1702. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1703. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1704. // 半年度日期就写入,否则不写入
  1705. if currDate.Month() == 6 || currDate.Month() == 12 {
  1706. dayList = append(dayList, currDate)
  1707. }
  1708. }
  1709. currDate = currDate.AddDate(0, 0, 1)
  1710. }
  1711. case "年度":
  1712. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1713. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1714. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1715. dayList = append(dayList, currDate)
  1716. }
  1717. }
  1718. }
  1719. return
  1720. }
  1721. // GetPredictEdbDayListByNum 根据期数获取预测指标日期列表
  1722. func GetPredictEdbDayListByNum(startDate time.Time, num int, frequency string) (dayList []time.Time) {
  1723. switch frequency {
  1724. case "日度":
  1725. for i := 1; i <= num; {
  1726. currDate := startDate.AddDate(0, 0, i)
  1727. //周六、日排除
  1728. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1729. continue
  1730. }
  1731. dayList = append(dayList, currDate)
  1732. i++
  1733. }
  1734. case "周度":
  1735. for i := 1; i <= num; {
  1736. dayList = append(dayList, startDate.AddDate(0, 0, i*7))
  1737. i++
  1738. }
  1739. case "旬度":
  1740. currDate := startDate
  1741. for i := 1; i <= num; {
  1742. nextDate := currDate.AddDate(0, 0, 1)
  1743. //每个月的10号、20号、最后一天,那么就写入
  1744. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1745. dayList = append(dayList, currDate)
  1746. i++
  1747. }
  1748. currDate = nextDate
  1749. }
  1750. case "月度":
  1751. currDate := startDate
  1752. for i := 1; i <= num; {
  1753. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1754. if !currDate.Equal(startDate) {
  1755. dayList = append(dayList, currDate)
  1756. i++
  1757. }
  1758. currDate = currDate.AddDate(0, 0, 1)
  1759. }
  1760. case "季度":
  1761. currDate := startDate
  1762. for i := 1; i <= num; {
  1763. // 每月的最后一天
  1764. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1765. if !currDate.Equal(startDate) {
  1766. // 季度日期就写入,否则不写入
  1767. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1768. dayList = append(dayList, currDate)
  1769. i++
  1770. }
  1771. }
  1772. currDate = currDate.AddDate(0, 0, 1)
  1773. }
  1774. case "半年度":
  1775. currDate := startDate
  1776. for i := 1; i <= num; {
  1777. // 每月的最后一天
  1778. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1779. if !currDate.Equal(startDate) {
  1780. // 半年度日期就写入,否则不写入
  1781. if currDate.Month() == 6 || currDate.Month() == 12 {
  1782. dayList = append(dayList, currDate)
  1783. i++
  1784. }
  1785. }
  1786. currDate = currDate.AddDate(0, 0, 1)
  1787. }
  1788. case "年度":
  1789. currDate := startDate
  1790. for i := 1; i <= num; {
  1791. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1792. if !currDate.Equal(startDate) {
  1793. dayList = append(dayList, currDate)
  1794. i++
  1795. }
  1796. }
  1797. }
  1798. return
  1799. }