common.go 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143
  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. // dateType 日期类型:1:00年至今,2:10年至今,3:15年至今,4:年初至今,5:自定义时间,6:起始日期至今 20:最近N年
  1437. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  1438. startDate = tmpStartDate
  1439. endDate = tmpEndDate
  1440. switch dateType {
  1441. case 1:
  1442. startDate = "2000-01-01"
  1443. endDate = ""
  1444. case 2:
  1445. startDate = "2010-01-01"
  1446. endDate = ""
  1447. case 3:
  1448. startDate = "2015-01-01"
  1449. endDate = ""
  1450. case 4:
  1451. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1452. startDate = "2021-01-01"
  1453. endDate = ""
  1454. case 5:
  1455. //startDate = startDate + "-01"
  1456. //endDate = endDate + "-01"
  1457. case 6:
  1458. //startDate = startDate + "-01"
  1459. endDate = ""
  1460. case 7:
  1461. startDate = "2018-01-01"
  1462. endDate = ""
  1463. case 8:
  1464. startDate = "2019-01-01"
  1465. endDate = ""
  1466. case 9:
  1467. startDate = "2020-01-01"
  1468. endDate = ""
  1469. case 11:
  1470. startDate = "2022-01-01"
  1471. endDate = ""
  1472. }
  1473. // 兼容日期错误
  1474. {
  1475. if strings.Count(startDate, "-") == 1 {
  1476. startDate = startDate + "-01"
  1477. }
  1478. if strings.Count(endDate, "-") == 1 {
  1479. endDate = endDate + "-01"
  1480. }
  1481. }
  1482. return
  1483. }
  1484. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
  1485. startDate = tmpStartDate
  1486. endDate = tmpEndDate
  1487. switch dateType {
  1488. case 1:
  1489. startDate = "2000-01-01"
  1490. endDate = ""
  1491. case 2:
  1492. startDate = "2010-01-01"
  1493. endDate = ""
  1494. case 3:
  1495. startDate = "2015-01-01"
  1496. endDate = ""
  1497. case 4:
  1498. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1499. startDate = "2021-01-01"
  1500. endDate = ""
  1501. case 5:
  1502. //startDate = startDate + "-01"
  1503. //endDate = endDate + "-01"
  1504. case 6:
  1505. //startDate = startDate + "-01"
  1506. endDate = ""
  1507. case 7:
  1508. startDate = "2018-01-01"
  1509. endDate = ""
  1510. case 8:
  1511. startDate = "2019-01-01"
  1512. endDate = ""
  1513. case 9:
  1514. startDate = "2020-01-01"
  1515. endDate = ""
  1516. case 11:
  1517. startDate = "2022-01-01"
  1518. endDate = ""
  1519. case DateTypeNYears:
  1520. if startYear == 0 { //默认取最近5年
  1521. startYear = 5
  1522. }
  1523. if yearMax == 0 {
  1524. return
  1525. }
  1526. startYear = startYear - 1
  1527. baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
  1528. startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  1529. endDate = ""
  1530. }
  1531. // 兼容日期错误
  1532. {
  1533. if strings.Count(startDate, "-") == 1 {
  1534. startDate = startDate + "-01"
  1535. }
  1536. if strings.Count(endDate, "-") == 1 {
  1537. endDate = endDate + "-01"
  1538. }
  1539. }
  1540. return
  1541. }
  1542. func TimeTransferString(format string, t time.Time) string {
  1543. str := t.Format(format)
  1544. if t.IsZero() {
  1545. return ""
  1546. }
  1547. return str
  1548. }
  1549. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  1550. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  1551. switch dateType {
  1552. case 1:
  1553. startDate = currDate.AddDate(0, -3, 0)
  1554. case 2:
  1555. startDate = currDate.AddDate(0, -6, 0)
  1556. case 3:
  1557. startDate = currDate.AddDate(-1, 0, 0)
  1558. case 4:
  1559. startDate = currDate.AddDate(-2, 0, 0)
  1560. case 5:
  1561. startDate = currDate.AddDate(-3, 0, 0)
  1562. case 6:
  1563. startDate = currDate.AddDate(-5, 0, 0)
  1564. case 7:
  1565. startDate = currDate.AddDate(-10, 0, 0)
  1566. }
  1567. return
  1568. }
  1569. // GetCeilNewNum 保留n位有效数字的向上取整
  1570. // @params num 实际数据
  1571. // @params baseLen 需要保留的有效位数
  1572. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  1573. if num >= 1 {
  1574. tmpNum := int(math.Ceil(num)) // 向上取整
  1575. str := strconv.Itoa(tmpNum)
  1576. lenStr := len(str)
  1577. if lenStr > baseLen {
  1578. newNumStr := str[0:baseLen]
  1579. newNumInt, _ := strconv.Atoi(newNumStr)
  1580. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1581. if newNum < num {
  1582. newNumInt += 1
  1583. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1584. }
  1585. } else {
  1586. newNum = float64(tmpNum)
  1587. }
  1588. return
  1589. } else if num > 0 {
  1590. // 这是小数
  1591. str := strconv.FormatFloat(num, 'f', -1, 64)
  1592. // 去除小数点和负号
  1593. str = removeDecimalPoint(str)
  1594. // 计算字符串长度
  1595. lenStr := len(str)
  1596. if lenStr > baseLen {
  1597. newNumStr := str[0:baseLen]
  1598. newNumInt, _ := strconv.Atoi(newNumStr)
  1599. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1600. if newNum < num {
  1601. newNumInt += 1
  1602. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1603. }
  1604. } else {
  1605. newNum = num
  1606. }
  1607. } else if num > -1 {
  1608. // 这是小数
  1609. str := strconv.FormatFloat(num, 'f', -1, 64)
  1610. // 去除小数点和负号
  1611. str = removeDecimalPoint(str)
  1612. // 计算字符串长度
  1613. lenStr := len(str)
  1614. if lenStr > baseLen {
  1615. newNumStr := str[0:baseLen]
  1616. newNumInt, _ := strconv.Atoi(newNumStr)
  1617. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1618. newNum = -newNum
  1619. if newNum < num {
  1620. newNumInt -= 1
  1621. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1622. newNum = -newNum
  1623. }
  1624. } else {
  1625. newNum = num
  1626. }
  1627. if newNum == -0 {
  1628. newNum = 0
  1629. }
  1630. } else { // 小于等于-1
  1631. tmpNumFloat := math.Abs(num)
  1632. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  1633. str := strconv.Itoa(tmpNum)
  1634. lenStr := len(str)
  1635. if lenStr > baseLen {
  1636. newNumStr := str[0:baseLen]
  1637. //fmt.Println("newNumStr:", newNumStr)
  1638. newNumInt, _ := strconv.Atoi(newNumStr)
  1639. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1640. newNum = -newNum
  1641. if newNum < num {
  1642. newNumInt -= 1
  1643. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1644. newNum = -newNum
  1645. }
  1646. } else {
  1647. newNum = float64(-tmpNum)
  1648. }
  1649. }
  1650. return
  1651. }
  1652. // GetFloorNewNum 保留n位有效数字的向下取整
  1653. // @params num 实际数据
  1654. // @params baseLen 需要保留的有效位数
  1655. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  1656. if num >= 1 {
  1657. tmpNum := int(math.Floor(num)) // 向上取整
  1658. str := strconv.Itoa(tmpNum)
  1659. lenStr := len(str)
  1660. if lenStr > baseLen {
  1661. newNumStr := str[0:baseLen]
  1662. newNumInt, _ := strconv.Atoi(newNumStr)
  1663. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1664. if newNum < num {
  1665. newNumInt -= 1
  1666. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1667. }
  1668. } else {
  1669. newNum = float64(tmpNum)
  1670. }
  1671. return
  1672. } else if num > 0 {
  1673. // 这是小数
  1674. str := strconv.FormatFloat(num, 'f', -1, 64)
  1675. // 去除小数点和负号
  1676. str = removeDecimalPoint(str)
  1677. // 计算字符串长度
  1678. lenStr := len(str)
  1679. if lenStr > baseLen {
  1680. newNumStr := str[0:baseLen]
  1681. newNumInt, _ := strconv.Atoi(newNumStr)
  1682. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1683. if newNum > num {
  1684. newNumInt -= 1
  1685. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1686. }
  1687. } else {
  1688. newNum = num
  1689. }
  1690. } else if num > -1 {
  1691. // 这是小数
  1692. str := strconv.FormatFloat(num, 'f', -1, 64)
  1693. // 去除小数点和负号
  1694. str = removeDecimalPoint(str)
  1695. // 计算字符串长度
  1696. lenStr := len(str)
  1697. if lenStr > baseLen {
  1698. newNumStr := str[0:baseLen]
  1699. newNumInt, _ := strconv.Atoi(newNumStr)
  1700. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1701. newNum = -newNum
  1702. if newNum > num {
  1703. newNumInt += 1
  1704. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1705. newNum = -newNum
  1706. }
  1707. } else {
  1708. newNum = num
  1709. }
  1710. if newNum == -0 {
  1711. newNum = 0
  1712. }
  1713. } else { // 小于等于-1
  1714. tmpNumFloat := math.Abs(num)
  1715. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  1716. str := strconv.Itoa(tmpNum)
  1717. lenStr := len(str)
  1718. if lenStr > baseLen {
  1719. newNumStr := str[0:baseLen]
  1720. //fmt.Println("newNumStr:", newNumStr)
  1721. newNumInt, _ := strconv.Atoi(newNumStr)
  1722. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1723. newNum = -newNum
  1724. if newNum > num {
  1725. newNumInt += 1
  1726. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1727. newNum = -newNum
  1728. }
  1729. } else {
  1730. newNum = float64(-tmpNum)
  1731. }
  1732. }
  1733. return
  1734. }
  1735. // 去除小数点和负号
  1736. func removeDecimalPoint(str string) string {
  1737. // 去除小数点
  1738. str = str[strings.Index(str, ".")+1:]
  1739. return str
  1740. }
  1741. // GetPredictEdbDayListByEndDate 根据截止日期获取预测指标日期列表
  1742. func GetPredictEdbDayListByEndDate(startDate, endDate time.Time, frequency string) (dayList []time.Time) {
  1743. //if !utils.InArrayByStr([]string{"日度", "周度", "月度"}, frequency)
  1744. switch frequency {
  1745. case "日度":
  1746. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 1) {
  1747. //周六、日排除
  1748. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1749. continue
  1750. }
  1751. dayList = append(dayList, currDate)
  1752. }
  1753. case "周度":
  1754. //nextDate := startDate.AddDate(0, 0, 7)
  1755. for currDate := startDate.AddDate(0, 0, 7); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 7) {
  1756. dayList = append(dayList, currDate)
  1757. }
  1758. case "旬度":
  1759. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); {
  1760. nextDate := currDate.AddDate(0, 0, 1)
  1761. //每个月的10号、20号、最后一天,那么就写入
  1762. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1763. dayList = append(dayList, currDate)
  1764. }
  1765. currDate = nextDate
  1766. }
  1767. case "月度":
  1768. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1769. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1770. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1771. dayList = append(dayList, currDate)
  1772. }
  1773. currDate = currDate.AddDate(0, 0, 1)
  1774. }
  1775. case "季度":
  1776. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1777. // 每月的最后一天
  1778. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1779. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1780. // 季度日期就写入,否则不写入
  1781. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1782. dayList = append(dayList, currDate)
  1783. }
  1784. }
  1785. currDate = currDate.AddDate(0, 0, 1)
  1786. }
  1787. case "半年度":
  1788. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1789. // 每月的最后一天
  1790. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1791. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1792. // 半年度日期就写入,否则不写入
  1793. if currDate.Month() == 6 || currDate.Month() == 12 {
  1794. dayList = append(dayList, currDate)
  1795. }
  1796. }
  1797. currDate = currDate.AddDate(0, 0, 1)
  1798. }
  1799. case "年度":
  1800. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1801. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1802. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1803. dayList = append(dayList, currDate)
  1804. }
  1805. }
  1806. }
  1807. return
  1808. }
  1809. // GetPredictEdbDayListByNum 根据期数获取预测指标日期列表
  1810. func GetPredictEdbDayListByNum(startDate time.Time, num int, frequency string) (dayList []time.Time) {
  1811. switch frequency {
  1812. case "日度":
  1813. for i := 1; i <= num; {
  1814. currDate := startDate.AddDate(0, 0, i)
  1815. //周六、日排除
  1816. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1817. continue
  1818. }
  1819. dayList = append(dayList, currDate)
  1820. i++
  1821. }
  1822. case "周度":
  1823. for i := 1; i <= num; {
  1824. dayList = append(dayList, startDate.AddDate(0, 0, i*7))
  1825. i++
  1826. }
  1827. case "旬度":
  1828. currDate := startDate
  1829. for i := 1; i <= num; {
  1830. nextDate := currDate.AddDate(0, 0, 1)
  1831. //每个月的10号、20号、最后一天,那么就写入
  1832. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1833. dayList = append(dayList, currDate)
  1834. i++
  1835. }
  1836. currDate = nextDate
  1837. }
  1838. case "月度":
  1839. currDate := startDate
  1840. for i := 1; i <= num; {
  1841. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1842. if !currDate.Equal(startDate) {
  1843. dayList = append(dayList, currDate)
  1844. i++
  1845. }
  1846. currDate = currDate.AddDate(0, 0, 1)
  1847. }
  1848. case "季度":
  1849. currDate := startDate
  1850. for i := 1; i <= num; {
  1851. // 每月的最后一天
  1852. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1853. if !currDate.Equal(startDate) {
  1854. // 季度日期就写入,否则不写入
  1855. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1856. dayList = append(dayList, currDate)
  1857. i++
  1858. }
  1859. }
  1860. currDate = currDate.AddDate(0, 0, 1)
  1861. }
  1862. case "半年度":
  1863. currDate := startDate
  1864. for i := 1; i <= num; {
  1865. // 每月的最后一天
  1866. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1867. if !currDate.Equal(startDate) {
  1868. // 半年度日期就写入,否则不写入
  1869. if currDate.Month() == 6 || currDate.Month() == 12 {
  1870. dayList = append(dayList, currDate)
  1871. i++
  1872. }
  1873. }
  1874. currDate = currDate.AddDate(0, 0, 1)
  1875. }
  1876. case "年度":
  1877. currDate := startDate
  1878. for i := 1; i <= num; {
  1879. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1880. if !currDate.Equal(startDate) {
  1881. dayList = append(dayList, currDate)
  1882. i++
  1883. }
  1884. }
  1885. }
  1886. return
  1887. }
  1888. // FormatTableDataShowValue 格式化自定表格显示数据
  1889. func FormatTableDataShowValue(x float64) (res string) {
  1890. if x > 1 || x < -1 {
  1891. res = decimal.NewFromFloat(x).Round(2).String()
  1892. return
  1893. }
  1894. // 介于-1到1之间
  1895. xStr := strconv.FormatFloat(x, 'f', -10, 64)
  1896. // 使用 strings.Split 函数将小数拆分为整数部分和小数部分
  1897. xParts := strings.Split(xStr, ".")
  1898. if len(xParts) < 2 {
  1899. res = fmt.Sprint(x)
  1900. return
  1901. }
  1902. // 计算小数部分的长度,即小数点后面的位数
  1903. xDecimals := len(xParts[1])
  1904. if xDecimals > 2 {
  1905. parts := xParts[1]
  1906. // 小数点后小于等于两位, 直接拼接返回
  1907. partLen := len(xParts[1])
  1908. if partLen <= 2 {
  1909. res = xParts[0] + "." + parts
  1910. return
  1911. }
  1912. // 找出第一个有效数字, 算出n
  1913. one := 0
  1914. for k, p := range parts {
  1915. // 48->0
  1916. if p != 48 {
  1917. if one == 0 {
  1918. one = k + 1
  1919. }
  1920. }
  1921. }
  1922. n := partLen - one
  1923. if n >= 1 {
  1924. n -= 1
  1925. } else {
  1926. one -= 1
  1927. }
  1928. var partFloat float64
  1929. partInt, _ := strconv.Atoi(parts)
  1930. partFloat, _ = decimal.NewFromInt(int64(partInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(n)))).Float64()
  1931. partFloat = math.Round(partFloat)
  1932. partFloat, _ = decimal.NewFromFloat(partFloat).Div(decimal.NewFromFloat(math.Pow(10, float64(one+1)))).Float64()
  1933. resParts := strings.Split(fmt.Sprint(partFloat), ".")
  1934. resPart := ""
  1935. if len(resParts) > 1 {
  1936. resPart = resParts[1]
  1937. } else {
  1938. resPart = resParts[0]
  1939. }
  1940. res = xParts[0] + "." + resPart
  1941. }
  1942. if xDecimals < 2 {
  1943. xDecimalsStr := xParts[1]
  1944. x, _ = strconv.ParseFloat(xParts[0]+"."+xDecimalsStr, 64)
  1945. res = xParts[0] + "." + xDecimalsStr
  1946. }
  1947. return
  1948. }
  1949. func DealDateTimeZero(t time.Time, format string) (timeStr string) {
  1950. if !t.IsZero() {
  1951. timeStr = t.Format(format)
  1952. }
  1953. return
  1954. }