common.go 53 KB

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