common.go 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470
  1. package utils
  2. import (
  3. "bufio"
  4. "bytes"
  5. "crypto/hmac"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "crypto/sha256"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "github.com/PuerkitoBio/goquery"
  15. "github.com/microcosm-cc/bluemonday"
  16. "github.com/shopspring/decimal"
  17. xhtml "golang.org/x/net/html"
  18. "html"
  19. "image"
  20. "image/png"
  21. "io"
  22. "math"
  23. "math/rand"
  24. "net"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "os/exec"
  29. "path"
  30. "regexp"
  31. "sort"
  32. "strconv"
  33. "strings"
  34. "time"
  35. "unicode"
  36. )
  37. // 随机数种子
  38. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  39. func GetRandString(size int) string {
  40. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "!", "@", "#", "$", "%", "^", "&", "*"}
  41. randomSb := ""
  42. digitSize := len(allLetterDigit)
  43. for i := 0; i < size; i++ {
  44. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  45. }
  46. return randomSb
  47. }
  48. func GetRandStringNoSpecialChar(size int) string {
  49. 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"}
  50. randomSb := ""
  51. digitSize := len(allLetterDigit)
  52. for i := 0; i < size; i++ {
  53. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  54. }
  55. return randomSb
  56. }
  57. func StringsToJSON(str string) string {
  58. rs := []rune(str)
  59. jsons := ""
  60. for _, r := range rs {
  61. rint := int(r)
  62. if rint < 128 {
  63. jsons += string(r)
  64. } else {
  65. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  66. }
  67. }
  68. return jsons
  69. }
  70. // 序列化
  71. func ToString(v interface{}) string {
  72. data, _ := json.Marshal(v)
  73. return string(data)
  74. }
  75. // md5加密
  76. func MD5(data string) string {
  77. m := md5.Sum([]byte(data))
  78. return hex.EncodeToString(m[:])
  79. }
  80. // HmacMd5 HmacMd5加密
  81. func HmacMd5(key, data string) string {
  82. h := hmac.New(md5.New, []byte(key))
  83. h.Write([]byte(data))
  84. return hex.EncodeToString(h.Sum([]byte("")))
  85. }
  86. // 获取数字随机字符
  87. func GetRandDigit(n int) string {
  88. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  89. }
  90. // 获取随机数
  91. func GetRandNumber(n int) int {
  92. return rnd.Intn(n)
  93. }
  94. func GetRandInt(min, max int) int {
  95. if min >= max || min == 0 || max == 0 {
  96. return max
  97. }
  98. return rand.Intn(max-min) + min
  99. }
  100. func GetToday(format string) string {
  101. today := time.Now().Format(format)
  102. return today
  103. }
  104. // 获取今天剩余秒数
  105. func GetTodayLastSecond() time.Duration {
  106. today := GetToday(FormatDate) + " 23:59:59"
  107. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  108. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  109. }
  110. // 处理出生日期函数
  111. func GetBrithDate(idcard string) string {
  112. l := len(idcard)
  113. var s string
  114. if l == 15 {
  115. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  116. return s
  117. }
  118. if l == 18 {
  119. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  120. return s
  121. }
  122. return GetToday(FormatDate)
  123. }
  124. // 处理性别
  125. func WhichSexByIdcard(idcard string) string {
  126. var sexs = [2]string{"女", "男"}
  127. length := len(idcard)
  128. if length == 18 {
  129. sex, _ := strconv.Atoi(string(idcard[16]))
  130. return sexs[sex%2]
  131. } else if length == 15 {
  132. sex, _ := strconv.Atoi(string(idcard[14]))
  133. return sexs[sex%2]
  134. }
  135. return "男"
  136. }
  137. // SubFloatToString 截取小数点后几位
  138. func SubFloatToString(f float64, m int) string {
  139. n := strconv.FormatFloat(f, 'f', -1, 64)
  140. if n == "" {
  141. return ""
  142. }
  143. if m >= len(n) {
  144. return n
  145. }
  146. newn := strings.Split(n, ".")
  147. if m == 0 {
  148. return newn[0]
  149. }
  150. if len(newn) < 2 || m >= len(newn[1]) {
  151. return n
  152. }
  153. return newn[0] + "." + newn[1][:m]
  154. }
  155. // 截取小数点后几位
  156. func SubFloatToFloat(f float64, m int) float64 {
  157. newn := SubFloatToString(f, m)
  158. newf, _ := strconv.ParseFloat(newn, 64)
  159. return newf
  160. }
  161. // 截取小数点后几位
  162. func SubFloatToFloatStr(f float64, m int) string {
  163. newn := SubFloatToString(f, m)
  164. return newn
  165. }
  166. // 获取相差时间-年
  167. func GetYearDiffer(start_time, end_time string) int {
  168. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  169. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  170. age := t2.Year() - t1.Year()
  171. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  172. age--
  173. }
  174. return age
  175. }
  176. // 获取相差时间-秒
  177. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  178. diff := end_time.Unix() - start_time.Unix()
  179. return diff
  180. }
  181. func FixFloat(f float64, m int) float64 {
  182. newn := SubFloatToString(f+0.00000001, m)
  183. newf, _ := strconv.ParseFloat(newn, 64)
  184. return newf
  185. }
  186. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  187. func StrListToString(strList []string) (str string) {
  188. if len(strList) > 0 {
  189. for k, v := range strList {
  190. if k == 0 {
  191. str = v
  192. } else {
  193. str = str + "," + v
  194. }
  195. }
  196. return
  197. }
  198. return ""
  199. }
  200. // 数据没有记录
  201. func ErrNoRow() string {
  202. return "<QuerySeter> no row found"
  203. }
  204. // 校验邮箱格式
  205. func ValidateEmailFormatat(email string) bool {
  206. reg := regexp.MustCompile(RegularEmail)
  207. return reg.MatchString(email)
  208. }
  209. // 验证是否是手机号
  210. func ValidateMobileFormatat(mobileNum string) bool {
  211. reg := regexp.MustCompile(RegularMobile)
  212. return reg.MatchString(mobileNum)
  213. }
  214. // 判断文件是否存在
  215. func FileIsExist(filePath string) bool {
  216. _, err := os.Stat(filePath)
  217. return err == nil || os.IsExist(err)
  218. }
  219. // 获取图片扩展名
  220. func GetImgExt(file string) (ext string, err error) {
  221. var headerByte []byte
  222. headerByte = make([]byte, 8)
  223. fd, err := os.Open(file)
  224. if err != nil {
  225. return "", err
  226. }
  227. defer fd.Close()
  228. _, err = fd.Read(headerByte)
  229. if err != nil {
  230. return "", err
  231. }
  232. xStr := fmt.Sprintf("%x", headerByte)
  233. switch {
  234. case xStr == "89504e470d0a1a0a":
  235. ext = ".png"
  236. case xStr == "0000010001002020":
  237. ext = ".ico"
  238. case xStr == "0000020001002020":
  239. ext = ".cur"
  240. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  241. ext = ".gif"
  242. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  243. ext = ".tga"
  244. case xStr[:8] == "464f524d":
  245. ext = ".iff"
  246. case xStr[:8] == "52494646":
  247. ext = ".ani"
  248. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  249. ext = ".tiff"
  250. case xStr[:4] == "424d":
  251. ext = ".bmp"
  252. case xStr[:4] == "ffd8":
  253. ext = ".jpg"
  254. case xStr[:2] == "0a":
  255. ext = ".pcx"
  256. default:
  257. ext = ""
  258. }
  259. return ext, nil
  260. }
  261. // 保存图片
  262. func SaveImage(path string, img image.Image) (err error) {
  263. //需要保持的文件
  264. imgfile, err := os.Create(path)
  265. defer imgfile.Close()
  266. // 以PNG格式保存文件
  267. err = png.Encode(imgfile, img)
  268. return err
  269. }
  270. // 下载图片
  271. func DownloadImage(imgUrl string) (filePath string, err error) {
  272. imgPath := "./static/imgs/"
  273. fileName := path.Base(imgUrl)
  274. res, err := http.Get(imgUrl)
  275. if err != nil {
  276. fmt.Println("A error occurred!")
  277. return
  278. }
  279. defer res.Body.Close()
  280. // 获得get请求响应的reader对象
  281. reader := bufio.NewReaderSize(res.Body, 32*1024)
  282. filePath = imgPath + fileName
  283. file, err := os.Create(filePath)
  284. if err != nil {
  285. return
  286. }
  287. defer func() {
  288. file.Close()
  289. }()
  290. // 获得文件的writer对象
  291. writer := bufio.NewWriter(file)
  292. written, _ := io.Copy(writer, reader)
  293. fmt.Printf("Total length: %d \n", written)
  294. return
  295. }
  296. // DownloadFile 下载文件
  297. func DownloadFile(fileUrl, fileDir string) (filePath string, err error) {
  298. filePathDir := "./static/imgs/"
  299. if fileDir != `` {
  300. err = os.MkdirAll(fileDir, DIR_MOD)
  301. if err != nil {
  302. return
  303. }
  304. filePathDir = fileDir
  305. }
  306. fileName := path.Base(fileUrl)
  307. res, err := http.Get(fileUrl)
  308. if err != nil {
  309. fmt.Println("A error occurred!")
  310. return
  311. }
  312. defer res.Body.Close()
  313. // 获得get请求响应的reader对象
  314. reader := bufio.NewReaderSize(res.Body, 32*1024)
  315. filePath = filePathDir + GetRandString(4) + fileName
  316. file, err := os.Create(filePath)
  317. if err != nil {
  318. return
  319. }
  320. defer func() {
  321. file.Close()
  322. }()
  323. // 获得文件的writer对象
  324. writer := bufio.NewWriter(file)
  325. _, _ = io.Copy(writer, reader)
  326. //fmt.Printf("Total length: %d \n", written)
  327. return
  328. }
  329. // 保存base64数据为文件
  330. func SaveBase64ToFile(content, path string) error {
  331. data, err := base64.StdEncoding.DecodeString(content)
  332. if err != nil {
  333. return err
  334. }
  335. f, err := os.Create(path)
  336. defer f.Close()
  337. if err != nil {
  338. return err
  339. }
  340. f.Write(data)
  341. return nil
  342. }
  343. func SaveBase64ToFileBySeek(content, path string) (err error) {
  344. data, err := base64.StdEncoding.DecodeString(content)
  345. exist, err := PathExists(path)
  346. if err != nil {
  347. return
  348. }
  349. if !exist {
  350. f, err := os.Create(path)
  351. if err != nil {
  352. return err
  353. }
  354. n, _ := f.Seek(0, 2)
  355. // 从末尾的偏移量开始写入内容
  356. _, err = f.WriteAt([]byte(data), n)
  357. defer f.Close()
  358. } else {
  359. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  360. if err != nil {
  361. return err
  362. }
  363. n, _ := f.Seek(0, 2)
  364. // 从末尾的偏移量开始写入内容
  365. _, err = f.WriteAt([]byte(data), n)
  366. defer f.Close()
  367. }
  368. return nil
  369. }
  370. func PathExists(path string) (bool, error) {
  371. _, err := os.Stat(path)
  372. if err == nil {
  373. return true, nil
  374. }
  375. if os.IsNotExist(err) {
  376. return false, nil
  377. }
  378. return false, err
  379. }
  380. func StartIndex(page, pagesize int) int {
  381. if page > 1 {
  382. return (page - 1) * pagesize
  383. }
  384. return 0
  385. }
  386. func PageCount(count, pagesize int) int {
  387. if count%pagesize > 0 {
  388. return count/pagesize + 1
  389. } else {
  390. return count / pagesize
  391. }
  392. }
  393. func TrimHtml(src string) string {
  394. //将HTML标签全转换成小写
  395. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  396. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  397. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  398. src = re.ReplaceAllString(src, "")
  399. re, _ = regexp.Compile("class[\\S\\s]+?>")
  400. src = re.ReplaceAllString(src, "")
  401. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  402. src = re.ReplaceAllString(src, "")
  403. src = strings.ReplaceAll(src, "&nbsp;", " ")
  404. return strings.TrimSpace(src)
  405. }
  406. //1556164246 -> 2019-04-25 03:50:46 +0000
  407. //timestamp
  408. func TimeToTimestamp() {
  409. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  410. }
  411. func ToUnicode(text string) string {
  412. textQuoted := strconv.QuoteToASCII(text)
  413. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  414. return textUnquoted
  415. }
  416. func VersionToInt(version string) int {
  417. version = strings.Replace(version, ".", "", -1)
  418. n, _ := strconv.Atoi(version)
  419. return n
  420. }
  421. func IsCheckInList(list []int, s int) bool {
  422. for _, v := range list {
  423. if v == s {
  424. return true
  425. }
  426. }
  427. return false
  428. }
  429. func round(num float64) int {
  430. return int(num + math.Copysign(0.5, num))
  431. }
  432. func toFixed(num float64, precision int) float64 {
  433. output := math.Pow(10, float64(precision))
  434. return float64(round(num*output)) / output
  435. }
  436. // GetWilsonScore returns Wilson Score
  437. func GetWilsonScore(p, n float64) float64 {
  438. if p == 0 && n == 0 {
  439. return 0
  440. }
  441. 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)
  442. }
  443. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  444. func ChangeWordsToNum(str string) (numStr string) {
  445. words := ([]rune)(str)
  446. num := 0
  447. n := 0
  448. for i := 0; i < len(words); i++ {
  449. word := string(words[i : i+1])
  450. switch word {
  451. case "万":
  452. if n == 0 {
  453. n = 1
  454. }
  455. n = n * 10000
  456. num = num*10000 + n
  457. n = 0
  458. case "千":
  459. if n == 0 {
  460. n = 1
  461. }
  462. n = n * 1000
  463. num += n
  464. n = 0
  465. case "百":
  466. if n == 0 {
  467. n = 1
  468. }
  469. n = n * 100
  470. num += n
  471. n = 0
  472. case "十":
  473. if n == 0 {
  474. n = 1
  475. }
  476. n = n * 10
  477. num += n
  478. n = 0
  479. case "一":
  480. n += 1
  481. case "二":
  482. n += 2
  483. case "三":
  484. n += 3
  485. case "四":
  486. n += 4
  487. case "五":
  488. n += 5
  489. case "六":
  490. n += 6
  491. case "七":
  492. n += 7
  493. case "八":
  494. n += 8
  495. case "九":
  496. n += 9
  497. case "零":
  498. default:
  499. if n > 0 {
  500. num += n
  501. n = 0
  502. }
  503. if num == 0 {
  504. numStr += word
  505. } else {
  506. numStr += strconv.Itoa(num) + word
  507. num = 0
  508. }
  509. }
  510. }
  511. if n > 0 {
  512. num += n
  513. n = 0
  514. }
  515. if num != 0 {
  516. numStr += strconv.Itoa(num)
  517. }
  518. return
  519. }
  520. func Sha1(data string) string {
  521. sha1 := sha1.New()
  522. sha1.Write([]byte(data))
  523. return hex.EncodeToString(sha1.Sum([]byte("")))
  524. }
  525. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  526. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  527. out, err := exec.Command("bash", "-c", cmd).Output()
  528. if err != nil {
  529. return
  530. }
  531. outTimes := string(out)
  532. fmt.Println("outTimes:", outTimes)
  533. if outTimes != "" {
  534. timeArr := strings.Split(outTimes, ":")
  535. h := timeArr[0]
  536. m := timeArr[1]
  537. s := timeArr[2]
  538. hInt, err := strconv.Atoi(h)
  539. if err != nil {
  540. return playSeconds, err
  541. }
  542. mInt, err := strconv.Atoi(m)
  543. if err != nil {
  544. return playSeconds, err
  545. }
  546. s = strings.Trim(s, " ")
  547. s = strings.Trim(s, "\n")
  548. sInt, err := strconv.ParseFloat(s, 64)
  549. if err != nil {
  550. return playSeconds, err
  551. }
  552. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  553. }
  554. return
  555. }
  556. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  557. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  558. tradeCode = strings.Trim(tradeCode, " ")
  559. tradeCodeInt, err := strconv.Atoi(tradeCode)
  560. if err != nil {
  561. return
  562. }
  563. tradeCodeInt = tradeCodeInt + 1
  564. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  565. return
  566. }
  567. // excel日期字段格式化 yyyy-mm-dd
  568. func ConvertToFormatDay(excelDaysString string) string {
  569. // 2006-01-02 距离 1900-01-01的天数
  570. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  571. curDiffDay := excelDaysString
  572. b, _ := strconv.Atoi(curDiffDay)
  573. // 获取excel的日期距离2006-01-02的天数
  574. realDiffDay := b - baseDiffDay
  575. //fmt.Println("realDiffDay:",realDiffDay)
  576. // 距离2006-01-02 秒数
  577. realDiffSecond := realDiffDay * 24 * 3600
  578. //fmt.Println("realDiffSecond:",realDiffSecond)
  579. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  580. baseOriginSecond := 1136185445
  581. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  582. return resultTime
  583. }
  584. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  585. func GetDaysDiff1900(date string) int {
  586. // 将字符串转换为时间类型
  587. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  588. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  589. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  590. if err != nil {
  591. return 0
  592. }
  593. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  594. if err != nil {
  595. return 0
  596. }
  597. // 计算两个日期之间的天数差值
  598. duration := tEnd.Sub(tStart).Hours() / 24
  599. days := int(duration)
  600. return days
  601. }
  602. func CheckPwd(pwd string) bool {
  603. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  604. reg := regexp.MustCompile(compile)
  605. flag := reg.MatchString(pwd)
  606. return flag
  607. }
  608. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  609. // 数字月份必须前置补零
  610. if len(myMonth) == 1 {
  611. myMonth = "0" + myMonth
  612. }
  613. yInt, _ := strconv.Atoi(myYear)
  614. timeLayout := "2006-01-02 15:04:05"
  615. loc, _ := time.LoadLocation("Local")
  616. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  617. newMonth := theTime.Month()
  618. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  619. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  620. return t1, t2
  621. }
  622. // TrimStr 移除字符串中的空格
  623. func TrimStr(str string) (str2 string) {
  624. if str == "" {
  625. return str
  626. }
  627. return strings.Replace(str, " ", "", -1)
  628. }
  629. // TrimLRStr 移除字符串前后的空格
  630. func TrimLRStr(str string) (str2 string) {
  631. if str == "" {
  632. return str
  633. }
  634. str2 = strings.TrimLeft(str, " ")
  635. str2 = strings.TrimRight(str2, " ")
  636. return
  637. }
  638. // 字符串转换为time
  639. func StrTimeToTime(strTime string) time.Time {
  640. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  641. loc, _ := time.LoadLocation("Local") //重要:获取时区
  642. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  643. return resultTime
  644. }
  645. // 字符串类型时间转周几
  646. func StrDateTimeToWeek(strTime string) string {
  647. var WeekDayMap = map[string]string{
  648. "Monday": "周一",
  649. "Tuesday": "周二",
  650. "Wednesday": "周三",
  651. "Thursday": "周四",
  652. "Friday": "周五",
  653. "Saturday": "周六",
  654. "Sunday": "周日",
  655. }
  656. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  657. startday, _ := time.Parse("2006-01-02", ctime)
  658. staweek_int := startday.Weekday().String()
  659. return WeekDayMap[staweek_int]
  660. }
  661. // EnWeekToCnWeek 英文周几转中文周几
  662. func EnWeekToCnWeek(enWeekStr string) string {
  663. var WeekDayMap = map[string]string{
  664. "Monday": "周一",
  665. "Tuesday": "周二",
  666. "Wednesday": "周三",
  667. "Thursday": "周四",
  668. "Friday": "周五",
  669. "Saturday": "周六",
  670. "Sunday": "周日",
  671. }
  672. cnWeekStr, ok := WeekDayMap[enWeekStr]
  673. if !ok {
  674. cnWeekStr = `周一`
  675. }
  676. return cnWeekStr
  677. }
  678. // 时间格式转年月日字符串
  679. func TimeToStrYmd(time2 time.Time) string {
  680. var Ymd string
  681. year := time2.Year()
  682. month := time2.Format("1")
  683. day1 := time.Now().Day()
  684. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  685. return Ymd
  686. }
  687. // 时间格式去掉时分秒
  688. func TimeRemoveHms(strTime string) string {
  689. var Ymd string
  690. var resultTime = StrTimeToTime(strTime)
  691. year := resultTime.Year()
  692. month := resultTime.Format("01")
  693. day1 := resultTime.Day()
  694. if day1 < 10 {
  695. Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
  696. } else {
  697. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  698. }
  699. return Ymd
  700. }
  701. // 时间格式去掉时分秒
  702. func TimeRemoveHms2(strTime string) string {
  703. var Ymd string
  704. var resultTime = StrTimeToTime(strTime)
  705. year := resultTime.Year()
  706. month := resultTime.Format("01")
  707. day1 := resultTime.Day()
  708. if day1 < 10 {
  709. Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
  710. } else {
  711. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  712. }
  713. return Ymd
  714. }
  715. // 文章上一次编辑时间
  716. func ArticleLastTime(strTime string) string {
  717. var newTime string
  718. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  719. diffTime := time.Now().Unix() - stamp.Unix()
  720. if diffTime <= 60 {
  721. newTime = "当前"
  722. } else if diffTime < 60*60 {
  723. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  724. } else if diffTime < 24*60*60 {
  725. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  726. } else if diffTime < 30*24*60*60 {
  727. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  728. } else if diffTime < 12*30*24*60*60 {
  729. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  730. } else {
  731. newTime = "1年前"
  732. }
  733. return newTime
  734. }
  735. // 人民币小写转大写
  736. func ConvertNumToCny(num float64) (str string, err error) {
  737. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  738. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  739. // log.Println(sliceUnit[:len(sliceUnit)-2])
  740. s := sliceUnit[len(sliceUnit)-len(strNum):]
  741. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  742. for k, v := range strNum[:] {
  743. str = str + upperDigitUnit[string(v)] + s[k]
  744. }
  745. reg, err := regexp.Compile(`零角零分$`)
  746. str = reg.ReplaceAllString(str, "整")
  747. reg, err = regexp.Compile(`零角`)
  748. str = reg.ReplaceAllString(str, "零")
  749. reg, err = regexp.Compile(`零分$`)
  750. str = reg.ReplaceAllString(str, "整")
  751. reg, err = regexp.Compile(`零[仟佰拾]`)
  752. str = reg.ReplaceAllString(str, "零")
  753. reg, err = regexp.Compile(`零{2,}`)
  754. str = reg.ReplaceAllString(str, "零")
  755. reg, err = regexp.Compile(`零亿`)
  756. str = reg.ReplaceAllString(str, "亿")
  757. reg, err = regexp.Compile(`零万`)
  758. str = reg.ReplaceAllString(str, "万")
  759. reg, err = regexp.Compile(`零*元`)
  760. str = reg.ReplaceAllString(str, "元")
  761. reg, err = regexp.Compile(`亿零{0, 3}万`)
  762. str = reg.ReplaceAllString(str, "^元")
  763. reg, err = regexp.Compile(`零元`)
  764. str = reg.ReplaceAllString(str, "零")
  765. return
  766. }
  767. // GetNowWeekMonday 获取本周周一的时间
  768. func GetNowWeekMonday() time.Time {
  769. offset := int(time.Monday - time.Now().Weekday())
  770. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  771. offset = -6
  772. }
  773. mondayTime := time.Now().AddDate(0, 0, offset)
  774. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  775. return mondayTime
  776. }
  777. // GetNowWeekLastDay 获取本周最后一天的时间
  778. func GetNowWeekLastDay() time.Time {
  779. offset := int(time.Monday - time.Now().Weekday())
  780. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  781. offset = -6
  782. }
  783. firstDayTime := time.Now().AddDate(0, 0, offset)
  784. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  785. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  786. return lastDayTime
  787. }
  788. // GetNowMonthFirstDay 获取本月第一天的时间
  789. func GetNowMonthFirstDay() time.Time {
  790. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  791. return nowMonthFirstDay
  792. }
  793. // GetNowMonthLastDay 获取本月最后一天的时间
  794. func GetNowMonthLastDay() time.Time {
  795. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  796. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  797. return nowMonthLastDay
  798. }
  799. // GetNowQuarterFirstDay 获取本季度第一天的时间
  800. func GetNowQuarterFirstDay() time.Time {
  801. month := int(time.Now().Month())
  802. var nowQuarterFirstDay time.Time
  803. if month >= 1 && month <= 3 {
  804. //1月1号
  805. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  806. } else if month >= 4 && month <= 6 {
  807. //4月1号
  808. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  809. } else if month >= 7 && month <= 9 {
  810. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  811. } else {
  812. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  813. }
  814. return nowQuarterFirstDay
  815. }
  816. // GetNowQuarterLastDay 获取本季度最后一天的时间
  817. func GetNowQuarterLastDay() time.Time {
  818. month := int(time.Now().Month())
  819. var nowQuarterLastDay time.Time
  820. if month >= 1 && month <= 3 {
  821. //03-31 23:59:59
  822. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  823. } else if month >= 4 && month <= 6 {
  824. //06-30 23:59:59
  825. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  826. } else if month >= 7 && month <= 9 {
  827. //09-30 23:59:59
  828. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  829. } else {
  830. //12-31 23:59:59
  831. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  832. }
  833. return nowQuarterLastDay
  834. }
  835. // GetNowHalfYearFirstDay 获取当前半年的第一天的时间
  836. func GetNowHalfYearFirstDay() time.Time {
  837. month := int(time.Now().Month())
  838. var nowHalfYearLastDay time.Time
  839. if month >= 1 && month <= 6 {
  840. //03-31 23:59:59
  841. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  842. } else {
  843. //12-31 23:59:59
  844. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  845. }
  846. return nowHalfYearLastDay
  847. }
  848. // GetNowHalfYearLastDay 获取当前半年的最后一天的时间
  849. func GetNowHalfYearLastDay() time.Time {
  850. month := int(time.Now().Month())
  851. var nowHalfYearLastDay time.Time
  852. if month >= 1 && month <= 6 {
  853. //03-31 23:59:59
  854. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  855. } else {
  856. //12-31 23:59:59
  857. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  858. }
  859. return nowHalfYearLastDay
  860. }
  861. // GetNowYearFirstDay 获取当前年的最后一天的时间
  862. func GetNowYearFirstDay() time.Time {
  863. //12-31 23:59:59
  864. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  865. return nowYearFirstDay
  866. }
  867. // GetNowYearLastDay 获取当前年的最后一天的时间
  868. func GetNowYearLastDay() time.Time {
  869. //12-31 23:59:59
  870. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  871. return nowYearLastDay
  872. }
  873. // CalculationDate 计算两个日期之间相差n年m月y天
  874. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  875. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  876. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  877. numYear := endDate.Year() - startDate.Year()
  878. numMonth := int(endDate.Month()) - int(startDate.Month())
  879. numDay := 0
  880. //获取截止月的总天数
  881. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  882. //获取截止月的前一个月
  883. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  884. //获取截止日期的上一个月的总天数
  885. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  886. //获取开始日期的的月份总天数
  887. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  888. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  889. if endDate.Day() == endDateDays {
  890. numDay = startDateMonthDays - startDate.Day() + 1
  891. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  892. if numDay == startDateMonthDays {
  893. numMonth++
  894. numDay = 0
  895. //超过月份了,那么年份加1
  896. if numMonth == 12 {
  897. numYear++
  898. numMonth = 0
  899. }
  900. }
  901. } else {
  902. numDay = endDate.Day() - startDate.Day() + 1
  903. }
  904. //天数小于0,那么向月份借一位
  905. if numDay < 0 {
  906. //向上一个月借一个月的天数
  907. numDay += endDatePrevMonthDays
  908. //总月份减去一个月
  909. numMonth = numMonth - 1
  910. }
  911. //月份小于0,那么向年份借一位
  912. if numMonth < 0 {
  913. //向上一个年借12个月
  914. numMonth += 12
  915. //总年份减去一年
  916. numYear = numYear - 1
  917. }
  918. if numYear < 0 {
  919. err = errors.New("日期异常")
  920. return
  921. }
  922. if numYear > 0 {
  923. beetweenDay += fmt.Sprint(numYear, "年")
  924. }
  925. if numMonth > 0 {
  926. beetweenDay += fmt.Sprint(numMonth, "个月")
  927. }
  928. if numDay > 0 {
  929. beetweenDay += fmt.Sprint(numDay, "天")
  930. }
  931. return
  932. }
  933. // FormatPrice 格式化展示金额数字(财务金额展示,小数点前,每三位用,隔开) 1,234,567,898.55
  934. func FormatPrice(price float64) (str string) {
  935. str = decimal.NewFromFloat(price).String()
  936. length := len(str)
  937. if length < 4 {
  938. return str
  939. }
  940. arr := strings.Split(str, ".") //用小数点符号分割字符串,为数组接收
  941. length1 := len(arr[0])
  942. if length1 < 4 {
  943. return str
  944. }
  945. count := (length1 - 1) / 3
  946. for i := 0; i < count; i++ {
  947. arr[0] = arr[0][:length1-(i+1)*3] + "," + arr[0][length1-(i+1)*3:]
  948. }
  949. return strings.Join(arr, ".") //将一系列字符串连接为一个字符串,之间用sep来分隔。
  950. }
  951. // getMonthDay 获取某年某月有多少天
  952. func getMonthDay(year, month int) (days int) {
  953. if month != 2 {
  954. if month == 4 || month == 6 || month == 9 || month == 11 {
  955. days = 30
  956. } else {
  957. days = 31
  958. }
  959. } else {
  960. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  961. days = 29
  962. } else {
  963. days = 28
  964. }
  965. }
  966. return
  967. }
  968. func SaveToFile(content, path string) error {
  969. f, err := os.Create(path)
  970. defer f.Close()
  971. if err != nil {
  972. return err
  973. }
  974. f.Write([]byte(content))
  975. return nil
  976. }
  977. // 用户参会时间转换
  978. func GetAttendanceDetailSeconds(secondNum int) string {
  979. var timeStr string
  980. if secondNum <= 60 {
  981. if secondNum < 10 {
  982. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  983. } else {
  984. timeStr = strconv.Itoa(secondNum) + "''"
  985. }
  986. } else {
  987. var remainderStr string
  988. remainderNum := secondNum % 60
  989. minuteNum := secondNum / 60
  990. if remainderNum < 10 {
  991. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  992. } else {
  993. remainderStr = strconv.Itoa(remainderNum) + "''"
  994. }
  995. if minuteNum < 10 {
  996. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  997. } else {
  998. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  999. }
  1000. }
  1001. return timeStr
  1002. }
  1003. // SubStr 截取字符串(中文)
  1004. func SubStr(str string, subLen int) string {
  1005. strRune := []rune(str)
  1006. bodyRuneLen := len(strRune)
  1007. if bodyRuneLen > subLen {
  1008. bodyRuneLen = subLen
  1009. }
  1010. str = string(strRune[:bodyRuneLen])
  1011. return str
  1012. }
  1013. // HideString 给字段加***(从字符串中间替换,少于需要替换的长度,那么就补全*的长度)
  1014. // src 待*字符串
  1015. // hideLen 需要加*的长度
  1016. func HideString(src string, hideLen int) string {
  1017. if src == "" {
  1018. return src
  1019. }
  1020. str := []rune(src)
  1021. if hideLen == 0 {
  1022. hideLen = 4
  1023. }
  1024. hideStr := ""
  1025. for i := 0; i < hideLen; i++ {
  1026. hideStr += "*"
  1027. }
  1028. strLen := len(str)
  1029. // 字符长度是1
  1030. if strLen == 1 {
  1031. return string(str[:1]) + hideStr
  1032. }
  1033. //字符长度大于1,但是小于等于需要隐藏的字符长度,那么就隐藏中间,保留前后各一位字符
  1034. if strLen <= hideLen+2 {
  1035. return string(str[:1]) + hideStr + string(str[strLen-1:])
  1036. }
  1037. subLen := strLen - hideLen //剩余需要展示的字符长度
  1038. decimal.NewFromFloat(2)
  1039. frontLenDecimal := decimal.NewFromInt(int64(subLen)).Div(decimal.NewFromInt(2)) //前面需要展示的字符的长度
  1040. frontLen := frontLenDecimal.Floor().IntPart()
  1041. return string(str[:frontLen]) + hideStr + string(str[frontLen+int64(hideLen):])
  1042. }
  1043. func GetLocalIP() (ip string, err error) {
  1044. addrs, err := net.InterfaceAddrs()
  1045. if err != nil {
  1046. return
  1047. }
  1048. for _, addr := range addrs {
  1049. ipAddr, ok := addr.(*net.IPNet)
  1050. if !ok {
  1051. continue
  1052. }
  1053. if ipAddr.IP.IsLoopback() {
  1054. continue
  1055. }
  1056. if !ipAddr.IP.IsGlobalUnicast() {
  1057. continue
  1058. }
  1059. return ipAddr.IP.String(), nil
  1060. }
  1061. return
  1062. }
  1063. // GetNowWeekMonday 获取上一周周一的时间
  1064. func GetPreWeekMonday() time.Time {
  1065. nowMonday := GetNowWeekMonday()
  1066. return nowMonday.AddDate(0, 0, -7)
  1067. }
  1068. // GetNowWeekLastDay 获取上一周最后一天的时间
  1069. func GetPreWeekLastDay() time.Time {
  1070. nowSunday := GetNowWeekLastDay()
  1071. return nowSunday.AddDate(0, 0, -7)
  1072. }
  1073. // GetNextWeekMonday 获取下一周周一的时间
  1074. func GetNextWeekMonday() time.Time {
  1075. nowMonday := GetNowWeekMonday()
  1076. return nowMonday.AddDate(0, 0, 7)
  1077. }
  1078. // GetNextWeekLastDay 获取下一周最后一天的时间
  1079. func GetNextWeekLastDay() time.Time {
  1080. nowSunday := GetNowWeekLastDay()
  1081. return nowSunday.AddDate(0, 0, 7)
  1082. }
  1083. // 处理真实姓名,隐藏中间的部分,如:张*,张*将
  1084. func DealRealName(realName string) string {
  1085. if realName == "" {
  1086. return ""
  1087. }
  1088. names := bytes.Runes([]byte(realName))
  1089. fistName := names[0]
  1090. length := len(names)
  1091. if length == 2 {
  1092. return string(fistName) + "*"
  1093. } else if length > 2 {
  1094. lastName := names[length-1]
  1095. return string(fistName) + "*" + string(lastName)
  1096. }
  1097. return realName
  1098. }
  1099. // Implode php中的implode(用来将int型的切片转为string)
  1100. func Implode(idIntList []int) (str string) {
  1101. for _, id := range idIntList {
  1102. str += fmt.Sprint(id, ",")
  1103. }
  1104. str = str[:len(str)-1]
  1105. return
  1106. }
  1107. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  1108. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  1109. for _, id := range idIntList {
  1110. if id == searchId {
  1111. has = true
  1112. return
  1113. }
  1114. }
  1115. return
  1116. }
  1117. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  1118. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  1119. for _, id := range idStrList {
  1120. if id == searchId {
  1121. has = true
  1122. return
  1123. }
  1124. }
  1125. return
  1126. }
  1127. // Intersection 求两个切片的交集
  1128. func Intersection(a []string, b []string) (inter []string) {
  1129. // interacting on the smallest list first can potentailly be faster...but not by much, worse case is the same
  1130. low, high := a, b
  1131. if len(a) > len(b) {
  1132. low = b
  1133. high = a
  1134. }
  1135. done := false
  1136. for i, l := range low {
  1137. for j, h := range high {
  1138. // get future index values
  1139. f1 := i + 1
  1140. f2 := j + 1
  1141. if l == h {
  1142. inter = append(inter, h)
  1143. if f1 < len(low) && f2 < len(high) {
  1144. // if the future values aren't the same then that's the end of the intersection
  1145. if low[f1] != high[f2] {
  1146. done = true
  1147. }
  1148. }
  1149. // 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
  1150. high = high[:j+copy(high[j:], high[j+1:])]
  1151. break
  1152. }
  1153. }
  1154. // nothing in the future so we are done
  1155. if done {
  1156. break
  1157. }
  1158. }
  1159. return
  1160. }
  1161. // Minus 获取差集
  1162. func Minus(a []string, b []string) []string {
  1163. //var inter []string
  1164. inter := make([]string, 0)
  1165. mp := make(map[string]bool)
  1166. for _, s := range a {
  1167. if _, ok := mp[s]; !ok {
  1168. mp[s] = true
  1169. }
  1170. }
  1171. for _, s := range b {
  1172. if _, ok := mp[s]; ok {
  1173. delete(mp, s)
  1174. }
  1175. }
  1176. for key := range mp {
  1177. inter = append(inter, key)
  1178. }
  1179. return inter
  1180. }
  1181. // IntArr2joinString []int转字符串
  1182. func IntArr2joinString(arr []int, sep string) string {
  1183. if len(arr) == 0 {
  1184. return ""
  1185. }
  1186. strArr := make([]string, 0)
  1187. for _, v := range arr {
  1188. strArr = append(strArr, strconv.Itoa(v))
  1189. }
  1190. return strings.Join(strArr, sep)
  1191. }
  1192. // GetOneMonthFirstDay 获取某月的第一天的时间
  1193. func GetOneMonthFirstDay(time2 time.Time) time.Time {
  1194. nowMonthFirstDay := time.Date(time2.Year(), time2.Month(), 1, 0, 0, 0, 0, time.Now().Location())
  1195. return nowMonthFirstDay
  1196. }
  1197. // GetOneMonthLastDay 获取某月最后一天的时间
  1198. func GetOneMonthLastDay(time2 time.Time) time.Time {
  1199. nowMonthLastDay := time.Date(time2.Year(), time2.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1200. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  1201. return nowMonthLastDay
  1202. }
  1203. func GetReportContentTextSub(content string) (contentSub string, err error) {
  1204. content = html.UnescapeString(content)
  1205. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  1206. docText := doc.Text()
  1207. bodyRune := []rune(docText)
  1208. bodyRuneLen := len(bodyRune)
  1209. if bodyRuneLen > 200 {
  1210. bodyRuneLen = 200
  1211. }
  1212. body := string(bodyRune[:bodyRuneLen])
  1213. contentSub = body
  1214. contentSub = strings.Replace(body, "Powered by Froala Editor", "", -1)
  1215. return
  1216. }
  1217. // GetOrmInReplace 获取orm的in查询替换?的方法
  1218. func GetOrmInReplace(num int) string {
  1219. template := make([]string, num)
  1220. for i := 0; i < num; i++ {
  1221. template[i] = "?"
  1222. }
  1223. return strings.Join(template, ",")
  1224. }
  1225. // RevSlice 反转切片
  1226. func RevSlice(slice []int) []int {
  1227. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  1228. slice[i], slice[j] = slice[j], slice[i]
  1229. }
  1230. return slice
  1231. }
  1232. // ReplaceSpaceAndWrap 去除空格跟换行
  1233. func ReplaceSpaceAndWrap(str string) string {
  1234. // 去除空格
  1235. str = strings.Replace(str, " ", "", -1)
  1236. // 去除换行符
  1237. str = strings.Replace(str, "\n", "", -1)
  1238. return str
  1239. }
  1240. // JoinStr2IntArr 拼接字符串转[]int
  1241. func JoinStr2IntArr(str, sep string) (arr []int) {
  1242. arr = make([]int, 0)
  1243. if str == "" {
  1244. return
  1245. }
  1246. if sep == "" {
  1247. sep = ","
  1248. }
  1249. strArr := strings.Split(str, sep)
  1250. if len(strArr) == 0 {
  1251. return
  1252. }
  1253. for i := range strArr {
  1254. v, e := strconv.Atoi(strArr[i])
  1255. // int2str此处过滤掉无效int
  1256. if e != nil {
  1257. continue
  1258. }
  1259. arr = append(arr, v)
  1260. }
  1261. return
  1262. }
  1263. // 字符串转换为time类型
  1264. func StrDateToDate(strTime string) time.Time {
  1265. timeLayout := "2006-01-02" //转化所需模板
  1266. loc, _ := time.LoadLocation("Local") //重要:获取时区
  1267. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  1268. return resultTime
  1269. }
  1270. // GetTimeSubDay 计算两个时间的自然日期差(后面减去前面)
  1271. func GetTimeSubDay(t1, t2 time.Time) int {
  1272. var day int
  1273. swap := false
  1274. if t1.Unix() > t2.Unix() {
  1275. t1, t2 = t2, t1
  1276. swap = true
  1277. }
  1278. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  1279. day = int(t2.Sub(t1).Hours() / 24)
  1280. // 计算在t1+两个时间的余数之后天数是否有变化
  1281. if t1_.Day() != t1.Day() {
  1282. day += 1
  1283. }
  1284. if swap {
  1285. day = -day
  1286. }
  1287. return day
  1288. }
  1289. // 去除非中文字符串
  1290. func StrFilterNonChinese(src *string) {
  1291. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$")
  1292. strn := ""
  1293. for _, c := range *src {
  1294. if hzRegexp.MatchString(string(c)) {
  1295. strn += string(c)
  1296. }
  1297. }
  1298. *src = strn
  1299. }
  1300. // MinusInt 获取两个[]int差集
  1301. func MinusInt(a []int, b []int) []int {
  1302. var diff []int
  1303. mpA, mpB := make(map[int]bool), make(map[int]bool)
  1304. for _, v := range a {
  1305. mpA[v] = true
  1306. }
  1307. for _, v := range b {
  1308. mpB[v] = true
  1309. }
  1310. for _, s := range a {
  1311. if !mpB[s] {
  1312. diff = append(diff, s)
  1313. }
  1314. }
  1315. for _, s := range b {
  1316. if !mpA[s] {
  1317. diff = append(diff, s)
  1318. }
  1319. }
  1320. return diff
  1321. }
  1322. // IntersectInt 获取两个[]int交集
  1323. func IntersectInt(nums1 []int, nums2 []int) []int {
  1324. m := make(map[int]int)
  1325. var res []int
  1326. for _, num := range nums1 {
  1327. m[num]++
  1328. }
  1329. for _, num := range nums2 {
  1330. if m[num] > 0 {
  1331. res = append(res, num)
  1332. m[num]--
  1333. }
  1334. }
  1335. return res
  1336. }
  1337. // MapSorter 对于map 排序
  1338. type MapSorter []Item
  1339. type Item struct {
  1340. Key int
  1341. Val float64
  1342. }
  1343. func NewMapSorter(m map[int]float64) MapSorter {
  1344. ms := make(MapSorter, 0, len(m))
  1345. for k, v := range m {
  1346. ms = append(ms, Item{k, v})
  1347. }
  1348. return ms
  1349. }
  1350. func (ms MapSorter) Len() int {
  1351. return len(ms)
  1352. }
  1353. func (ms MapSorter) Less(i, j int) bool {
  1354. return ms[i].Val > ms[j].Val // 按值排序
  1355. //return ms[i].Key < ms[j].Key // 按键排序
  1356. }
  1357. func (ms MapSorter) Swap(i, j int) {
  1358. ms[i], ms[j] = ms[j], ms[i]
  1359. }
  1360. // FormatFileSize 字节的单位转换 保留两位小数
  1361. func FormatFileSize(fileSize int64) (size string) {
  1362. if fileSize < 1024 {
  1363. return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
  1364. } else if fileSize < (1024 * 1024) {
  1365. return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
  1366. } else if fileSize < (1024 * 1024 * 1024) {
  1367. return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
  1368. } else if fileSize < (1024 * 1024 * 1024 * 1024) {
  1369. return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
  1370. } else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
  1371. return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
  1372. } else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
  1373. return fmt.Sprintf("%.2fPB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
  1374. }
  1375. }
  1376. func GetDurationFormatBySecond(sec int) (formatString string) {
  1377. if sec == 0 {
  1378. formatString = "0分钟"
  1379. return
  1380. } else if sec <= 60 && sec > 0 {
  1381. formatString = "1分钟"
  1382. return
  1383. }
  1384. duration := time.Duration(int64(sec)) * time.Second
  1385. h := int(duration.Hours())
  1386. m := int(duration.Minutes()) % 60
  1387. //s := int(duration.Seconds()) % 60
  1388. if h > 0 {
  1389. formatString = fmt.Sprintf("%d小时", h)
  1390. }
  1391. if m > 0 {
  1392. formatString += fmt.Sprintf("%d分钟", m)
  1393. }
  1394. //if s > 0 {
  1395. // formatString += fmt.Sprintf("%d秒", s)
  1396. //}
  1397. return
  1398. }
  1399. // GetDaysBetween2Date 计算两个日期之间相差几天
  1400. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  1401. // 将字符串转化为Time格式
  1402. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  1403. if err != nil {
  1404. return 0, err
  1405. }
  1406. // 将字符串转化为Time格式
  1407. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  1408. if err != nil {
  1409. return 0, err
  1410. }
  1411. //计算相差天数
  1412. return int(date1.Sub(date2).Hours() / 24), nil
  1413. }
  1414. // GetFrequencyEn 获取频度的英文版
  1415. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1416. switch frequency {
  1417. case "日度":
  1418. frequencyEn = "day"
  1419. return
  1420. case "周度":
  1421. frequencyEn = "week"
  1422. return
  1423. case "旬度":
  1424. frequencyEn = "ten days"
  1425. return
  1426. case "月度":
  1427. frequencyEn = "month"
  1428. return
  1429. case "季度":
  1430. frequencyEn = "quarter"
  1431. return
  1432. case "年度":
  1433. frequencyEn = "year"
  1434. return
  1435. }
  1436. return
  1437. }
  1438. // GetLeadUnitEn 获取移动单位的英文版
  1439. func GetLeadUnitEn(unit string) (unitEn string) {
  1440. switch unit {
  1441. case "天":
  1442. unitEn = "day"
  1443. return
  1444. case "周":
  1445. unitEn = "week"
  1446. return
  1447. case "月":
  1448. unitEn = "month"
  1449. return
  1450. case "季":
  1451. unitEn = "quarter"
  1452. return
  1453. case "年":
  1454. unitEn = "year"
  1455. return
  1456. }
  1457. return
  1458. }
  1459. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  1460. // dateType 日期类型:1:00年至今,2:10年至今,3:15年至今,4:年初至今,5:自定义时间,6:起始日期至今 20:最近N年
  1461. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  1462. startDate = tmpStartDate
  1463. endDate = tmpEndDate
  1464. switch dateType {
  1465. case 1:
  1466. startDate = "2000-01-01"
  1467. endDate = ""
  1468. case 2:
  1469. startDate = "2010-01-01"
  1470. endDate = ""
  1471. case 3:
  1472. startDate = "2015-01-01"
  1473. endDate = ""
  1474. case 4:
  1475. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1476. startDate = "2021-01-01"
  1477. endDate = ""
  1478. case 5:
  1479. //startDate = startDate + "-01"
  1480. //endDate = endDate + "-01"
  1481. case 6:
  1482. //startDate = startDate + "-01"
  1483. endDate = ""
  1484. case 7:
  1485. startDate = "2018-01-01"
  1486. endDate = ""
  1487. case 8:
  1488. startDate = "2019-01-01"
  1489. endDate = ""
  1490. case 9:
  1491. startDate = "2020-01-01"
  1492. endDate = ""
  1493. case 11:
  1494. startDate = "2022-01-01"
  1495. endDate = ""
  1496. }
  1497. // 兼容日期错误
  1498. {
  1499. if strings.Count(startDate, "-") == 1 {
  1500. startDate = startDate + "-01"
  1501. }
  1502. if strings.Count(endDate, "-") == 1 {
  1503. endDate = endDate + "-01"
  1504. }
  1505. }
  1506. return
  1507. }
  1508. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
  1509. startDate = tmpStartDate
  1510. endDate = tmpEndDate
  1511. switch dateType {
  1512. case 1:
  1513. startDate = "2000-01-01"
  1514. endDate = ""
  1515. case 2:
  1516. startDate = "2010-01-01"
  1517. endDate = ""
  1518. case 3:
  1519. startDate = "2015-01-01"
  1520. endDate = ""
  1521. case 4:
  1522. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1523. startDate = "2021-01-01"
  1524. endDate = ""
  1525. case 5:
  1526. //startDate = startDate + "-01"
  1527. //endDate = endDate + "-01"
  1528. case 6:
  1529. //startDate = startDate + "-01"
  1530. endDate = ""
  1531. case 7:
  1532. startDate = "2018-01-01"
  1533. endDate = ""
  1534. case 8:
  1535. startDate = "2019-01-01"
  1536. endDate = ""
  1537. case 9:
  1538. startDate = "2020-01-01"
  1539. endDate = ""
  1540. case 11:
  1541. startDate = "2022-01-01"
  1542. endDate = ""
  1543. case DateTypeNYears:
  1544. if startYear == 0 { //默认取最近5年
  1545. startYear = 5
  1546. }
  1547. if yearMax == 0 {
  1548. return
  1549. }
  1550. startYear = startYear - 1
  1551. baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
  1552. startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  1553. endDate = ""
  1554. }
  1555. // 兼容日期错误
  1556. {
  1557. if strings.Count(startDate, "-") == 1 {
  1558. startDate = startDate + "-01"
  1559. }
  1560. if strings.Count(endDate, "-") == 1 {
  1561. endDate = endDate + "-01"
  1562. }
  1563. }
  1564. return
  1565. }
  1566. func TimeTransferString(format string, t time.Time) string {
  1567. str := t.Format(format)
  1568. if t.IsZero() {
  1569. return ""
  1570. }
  1571. return str
  1572. }
  1573. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  1574. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  1575. switch dateType {
  1576. case 1:
  1577. startDate = currDate.AddDate(0, -3, 0)
  1578. case 2:
  1579. startDate = currDate.AddDate(0, -6, 0)
  1580. case 3:
  1581. startDate = currDate.AddDate(-1, 0, 0)
  1582. case 4:
  1583. startDate = currDate.AddDate(-2, 0, 0)
  1584. case 5:
  1585. startDate = currDate.AddDate(-3, 0, 0)
  1586. case 6:
  1587. startDate = currDate.AddDate(-5, 0, 0)
  1588. case 7:
  1589. startDate = currDate.AddDate(-10, 0, 0)
  1590. }
  1591. return
  1592. }
  1593. // GetCeilNewNum 保留n位有效数字的向上取整
  1594. // @params num 实际数据
  1595. // @params baseLen 需要保留的有效位数
  1596. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  1597. if num >= 1 {
  1598. tmpNum := int(math.Ceil(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.Floor(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. // GetFloorNewNum 保留n位有效数字的向下取整
  1677. // @params num 实际数据
  1678. // @params baseLen 需要保留的有效位数
  1679. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  1680. if num >= 1 {
  1681. tmpNum := int(math.Floor(num)) // 向上取整
  1682. str := strconv.Itoa(tmpNum)
  1683. lenStr := len(str)
  1684. if lenStr > baseLen {
  1685. newNumStr := str[0:baseLen]
  1686. newNumInt, _ := strconv.Atoi(newNumStr)
  1687. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1688. if newNum < num {
  1689. newNumInt -= 1
  1690. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1691. }
  1692. } else {
  1693. newNum = float64(tmpNum)
  1694. }
  1695. return
  1696. } else if num > 0 {
  1697. // 这是小数
  1698. str := strconv.FormatFloat(num, 'f', -1, 64)
  1699. // 去除小数点和负号
  1700. str = removeDecimalPoint(str)
  1701. // 计算字符串长度
  1702. lenStr := len(str)
  1703. if lenStr > baseLen {
  1704. newNumStr := str[0:baseLen]
  1705. newNumInt, _ := strconv.Atoi(newNumStr)
  1706. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1707. if newNum > num {
  1708. newNumInt -= 1
  1709. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1710. }
  1711. } else {
  1712. newNum = num
  1713. }
  1714. } else if num > -1 {
  1715. // 这是小数
  1716. str := strconv.FormatFloat(num, 'f', -1, 64)
  1717. // 去除小数点和负号
  1718. str = removeDecimalPoint(str)
  1719. // 计算字符串长度
  1720. lenStr := len(str)
  1721. if lenStr > baseLen {
  1722. newNumStr := str[0:baseLen]
  1723. newNumInt, _ := strconv.Atoi(newNumStr)
  1724. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1725. newNum = -newNum
  1726. if newNum > num {
  1727. newNumInt += 1
  1728. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1729. newNum = -newNum
  1730. }
  1731. } else {
  1732. newNum = num
  1733. }
  1734. if newNum == -0 {
  1735. newNum = 0
  1736. }
  1737. } else { // 小于等于-1
  1738. tmpNumFloat := math.Abs(num)
  1739. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  1740. str := strconv.Itoa(tmpNum)
  1741. lenStr := len(str)
  1742. if lenStr > baseLen {
  1743. newNumStr := str[0:baseLen]
  1744. //fmt.Println("newNumStr:", newNumStr)
  1745. newNumInt, _ := strconv.Atoi(newNumStr)
  1746. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1747. newNum = -newNum
  1748. if newNum > num {
  1749. newNumInt += 1
  1750. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1751. newNum = -newNum
  1752. }
  1753. } else {
  1754. newNum = float64(-tmpNum)
  1755. }
  1756. }
  1757. return
  1758. }
  1759. // 去除小数点和负号
  1760. func removeDecimalPoint(str string) string {
  1761. // 去除小数点
  1762. str = str[strings.Index(str, ".")+1:]
  1763. return str
  1764. }
  1765. // GetPredictEdbDayListByEndDate 根据截止日期获取预测指标日期列表
  1766. func GetPredictEdbDayListByEndDate(startDate, endDate time.Time, frequency string) (dayList []time.Time) {
  1767. //if !utils.InArrayByStr([]string{"日度", "周度", "月度"}, frequency)
  1768. switch frequency {
  1769. case "日度":
  1770. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 1) {
  1771. //周六、日排除
  1772. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1773. continue
  1774. }
  1775. dayList = append(dayList, currDate)
  1776. }
  1777. case "周度":
  1778. //nextDate := startDate.AddDate(0, 0, 7)
  1779. for currDate := startDate.AddDate(0, 0, 7); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 7) {
  1780. dayList = append(dayList, currDate)
  1781. }
  1782. case "旬度":
  1783. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); {
  1784. nextDate := currDate.AddDate(0, 0, 1)
  1785. //每个月的10号、20号、最后一天,那么就写入
  1786. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1787. dayList = append(dayList, currDate)
  1788. }
  1789. currDate = nextDate
  1790. }
  1791. case "月度":
  1792. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1793. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1794. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1795. dayList = append(dayList, currDate)
  1796. }
  1797. currDate = currDate.AddDate(0, 0, 1)
  1798. }
  1799. case "季度":
  1800. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1801. // 每月的最后一天
  1802. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1803. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1804. // 季度日期就写入,否则不写入
  1805. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1806. dayList = append(dayList, currDate)
  1807. }
  1808. }
  1809. currDate = currDate.AddDate(0, 0, 1)
  1810. }
  1811. case "半年度":
  1812. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1813. // 每月的最后一天
  1814. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1815. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1816. // 半年度日期就写入,否则不写入
  1817. if currDate.Month() == 6 || currDate.Month() == 12 {
  1818. dayList = append(dayList, currDate)
  1819. }
  1820. }
  1821. currDate = currDate.AddDate(0, 0, 1)
  1822. }
  1823. case "年度":
  1824. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1825. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1826. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1827. dayList = append(dayList, currDate)
  1828. }
  1829. }
  1830. }
  1831. return
  1832. }
  1833. // GetPredictEdbDayListByNum 根据期数获取预测指标日期列表
  1834. func GetPredictEdbDayListByNum(startDate time.Time, num int, frequency string) (dayList []time.Time) {
  1835. switch frequency {
  1836. case "日度":
  1837. for i := 1; i <= num; {
  1838. currDate := startDate.AddDate(0, 0, i)
  1839. //周六、日排除
  1840. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1841. continue
  1842. }
  1843. dayList = append(dayList, currDate)
  1844. i++
  1845. }
  1846. case "周度":
  1847. for i := 1; i <= num; {
  1848. dayList = append(dayList, startDate.AddDate(0, 0, i*7))
  1849. i++
  1850. }
  1851. case "旬度":
  1852. currDate := startDate
  1853. for i := 1; i <= num; {
  1854. nextDate := currDate.AddDate(0, 0, 1)
  1855. //每个月的10号、20号、最后一天,那么就写入
  1856. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1857. dayList = append(dayList, currDate)
  1858. i++
  1859. }
  1860. currDate = nextDate
  1861. }
  1862. case "月度":
  1863. currDate := startDate
  1864. for i := 1; i <= num; {
  1865. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1866. if !currDate.Equal(startDate) {
  1867. dayList = append(dayList, currDate)
  1868. i++
  1869. }
  1870. currDate = currDate.AddDate(0, 0, 1)
  1871. }
  1872. case "季度":
  1873. currDate := startDate
  1874. for i := 1; i <= num; {
  1875. // 每月的最后一天
  1876. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1877. if !currDate.Equal(startDate) {
  1878. // 季度日期就写入,否则不写入
  1879. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1880. dayList = append(dayList, currDate)
  1881. i++
  1882. }
  1883. }
  1884. currDate = currDate.AddDate(0, 0, 1)
  1885. }
  1886. case "半年度":
  1887. currDate := startDate
  1888. for i := 1; i <= num; {
  1889. // 每月的最后一天
  1890. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1891. if !currDate.Equal(startDate) {
  1892. // 半年度日期就写入,否则不写入
  1893. if currDate.Month() == 6 || currDate.Month() == 12 {
  1894. dayList = append(dayList, currDate)
  1895. i++
  1896. }
  1897. }
  1898. currDate = currDate.AddDate(0, 0, 1)
  1899. }
  1900. case "年度":
  1901. currDate := startDate
  1902. for i := 1; i <= num; {
  1903. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1904. if !currDate.Equal(startDate) {
  1905. dayList = append(dayList, currDate)
  1906. i++
  1907. }
  1908. }
  1909. }
  1910. return
  1911. }
  1912. // FormatMixTableDataShowValue 格式化自定表格显示数据
  1913. func FormatMixTableDataShowValue(x float64) (res string) {
  1914. res = strconv.FormatFloat(x, 'f', -1, 64)
  1915. return
  1916. }
  1917. // FormatTableDataShowValue 格式化自定表格显示数据
  1918. func FormatTableDataShowValue(x float64) (res string) {
  1919. if x > 1 || x < -1 {
  1920. res = decimal.NewFromFloat(x).Round(2).String()
  1921. return
  1922. }
  1923. // 介于-1到1之间
  1924. xStr := strconv.FormatFloat(x, 'f', -10, 64)
  1925. // 使用 strings.Split 函数将小数拆分为整数部分和小数部分
  1926. xParts := strings.Split(xStr, ".")
  1927. if len(xParts) < 2 {
  1928. res = fmt.Sprint(x)
  1929. return
  1930. }
  1931. // 计算小数部分的长度,即小数点后面的位数
  1932. xDecimals := len(xParts[1])
  1933. if xDecimals > 2 {
  1934. parts := xParts[1]
  1935. // 小数点后小于等于两位, 直接拼接返回
  1936. partLen := len(xParts[1])
  1937. if partLen <= 2 {
  1938. res = xParts[0] + "." + parts
  1939. return
  1940. }
  1941. // 找出第一个有效数字, 算出n
  1942. one := 0
  1943. for k, p := range parts {
  1944. // 48->0
  1945. if p != 48 {
  1946. if one == 0 {
  1947. one = k + 1
  1948. }
  1949. }
  1950. }
  1951. n := partLen - one
  1952. if n >= 1 {
  1953. n -= 1
  1954. } else {
  1955. one -= 1
  1956. }
  1957. var partFloat float64
  1958. partInt, _ := strconv.Atoi(parts)
  1959. partFloat, _ = decimal.NewFromInt(int64(partInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(n)))).Float64()
  1960. partFloat = math.Round(partFloat)
  1961. partFloat, _ = decimal.NewFromFloat(partFloat).Div(decimal.NewFromFloat(math.Pow(10, float64(one+1)))).Float64()
  1962. resParts := strings.Split(fmt.Sprint(partFloat), ".")
  1963. resPart := ""
  1964. if len(resParts) > 1 {
  1965. resPart = resParts[1]
  1966. } else {
  1967. resPart = resParts[0]
  1968. }
  1969. res = xParts[0] + "." + resPart
  1970. }
  1971. if xDecimals <= 2 {
  1972. xDecimalsStr := xParts[1]
  1973. x, _ = strconv.ParseFloat(xParts[0]+"."+xDecimalsStr, 64)
  1974. res = xParts[0] + "." + xDecimalsStr
  1975. }
  1976. return
  1977. }
  1978. func DealDateTimeZero(t time.Time, format string) (timeStr string) {
  1979. if !t.IsZero() {
  1980. timeStr = t.Format(format)
  1981. }
  1982. return
  1983. }
  1984. // IsPercentage
  1985. // @Description: 判断一个字符串是否是百分比的字符串,并返回百分比的值(比如:50%,返回true 50)
  1986. // @author: Roc
  1987. // @datetime 2023-11-29 14:00:31
  1988. // @param input string
  1989. // @return bool
  1990. // @return string
  1991. func IsPercentage(input string) (bool, string) {
  1992. percentagePattern := `^-?(\d+(\.\d+)?)%$`
  1993. match, _ := regexp.MatchString(percentagePattern, input)
  1994. if match {
  1995. re := regexp.MustCompile(percentagePattern)
  1996. match := re.FindStringSubmatch(input)
  1997. // 区分负数和正数,确保返回结果包含负号(如有)
  1998. sign := "-"
  1999. if input[0] != '-' {
  2000. sign = ""
  2001. }
  2002. return true, sign + match[1]
  2003. }
  2004. return false, ""
  2005. }
  2006. // GetLikeKeyword
  2007. //
  2008. // @Description: 获取sql查询中的like查询字段
  2009. // @author: Roc
  2010. // @datetime2023-10-23 14:46:32
  2011. // @param keyword string
  2012. // @return string
  2013. func GetLikeKeyword(keyword string) string {
  2014. return `%` + keyword + `%`
  2015. }
  2016. // GetLikeKeywordPars
  2017. //
  2018. // @Description: 获取sql查询中的参数切片
  2019. // @author: Roc
  2020. // @datetime2023-10-23 14:50:18
  2021. // @param pars []interface{}
  2022. // @param keyword string
  2023. // @param num int
  2024. // @return newPars []interface{}
  2025. func GetLikeKeywordPars(pars []interface{}, keyword string, num int) (newPars []interface{}) {
  2026. newPars = pars
  2027. if newPars == nil {
  2028. newPars = make([]interface{}, 0)
  2029. }
  2030. for i := 1; i <= num; i++ {
  2031. newPars = append(newPars, `%`+keyword+`%`)
  2032. }
  2033. return
  2034. }
  2035. func GetSign(nonce, timestamp, appId, secret string) (sign string) {
  2036. signStrMap := map[string]string{
  2037. "nonce": nonce,
  2038. "timestamp": timestamp,
  2039. "appid": appId,
  2040. }
  2041. keys := make([]string, 0, len(signStrMap))
  2042. for k := range signStrMap {
  2043. keys = append(keys, k)
  2044. }
  2045. sort.Strings(keys)
  2046. var signStr string
  2047. for _, k := range keys {
  2048. signStr += k + "=" + signStrMap[k] + "&"
  2049. }
  2050. signStr = strings.Trim(signStr, "&")
  2051. fmt.Println("signStr:" + signStr)
  2052. sign = HmacSha256ToBase64(secret, signStr)
  2053. return
  2054. }
  2055. // HmacSha256ToBase64 将加密后的二进制转Base64字符串
  2056. func HmacSha256ToBase64(key string, data string) string {
  2057. return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
  2058. }
  2059. // HmacSha256 计算HmacSha256
  2060. // key 是加密所使用的key
  2061. // data 是加密的内容
  2062. func HmacSha256(key string, data string) []byte {
  2063. mac := hmac.New(sha256.New, []byte(key))
  2064. _, _ = mac.Write([]byte(data))
  2065. return mac.Sum(nil)
  2066. }
  2067. func PascalToSnake(s string) string {
  2068. var result []rune
  2069. for i, char := range s {
  2070. // 在大写字母前插入下划线,除非是第一个字母
  2071. if i > 0 && unicode.IsUpper(char) {
  2072. result = append(result, '_')
  2073. }
  2074. // 将字母转为小写
  2075. result = append(result, unicode.ToLower(char))
  2076. }
  2077. return string(result)
  2078. }
  2079. // ArrContainsStr函数检查一个字符串是否在字符串数组中
  2080. func ArrContainsStr(arr []string, str string) bool {
  2081. for _, v := range arr {
  2082. if v == str {
  2083. return true
  2084. }
  2085. }
  2086. return false
  2087. }
  2088. func GetColorMap() map[int]string {
  2089. colorMap := make(map[int]string)
  2090. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  2091. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  2092. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  2093. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  2094. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  2095. for k, v := range colors {
  2096. colorMap[k] = v
  2097. }
  2098. return colorMap
  2099. }
  2100. // 检查src属性是否以http或data:image开头
  2101. func isValidSrc(src string) bool {
  2102. // 使用Parse函数解析URL
  2103. parsedURL, err := url.Parse(src)
  2104. if err != nil {
  2105. validSchemes := regexp.MustCompile(`^data:image\/.*;base64,.*$`)
  2106. return validSchemes.MatchString(src)
  2107. }
  2108. if parsedURL.Host == "" || (parsedURL.Scheme != "http" && parsedURL.Scheme != "https") {
  2109. validSchemes := regexp.MustCompile(`^data:image\/.*;base64,.*$`)
  2110. return validSchemes.MatchString(src)
  2111. }
  2112. return true
  2113. }
  2114. // ContentXssCheck 校验文本中的JS代码
  2115. func ContentXssCheck(content string) (err error) {
  2116. // 解析HTML内容
  2117. node, err := xhtml.Parse(strings.NewReader(content))
  2118. if err != nil {
  2119. err = fmt.Errorf(" html.Parse Err: %v", err)
  2120. return
  2121. }
  2122. // 遍历解析后的节点树,查找特定标签
  2123. var visit func(n *xhtml.Node) error
  2124. visit = func(n *xhtml.Node) error {
  2125. if n.Type == xhtml.ElementNode {
  2126. lowerData := strings.ToLower(n.Data)
  2127. switch lowerData {
  2128. case "script", "javascript":
  2129. err = fmt.Errorf(" script is forbidden")
  2130. return err
  2131. default:
  2132. for _, attr := range n.Attr { //判断事件
  2133. lowerKey := strings.ToLower(attr.Key)
  2134. lowerVal := strings.ToLower(attr.Val)
  2135. if lowerKey == "src" || lowerKey == "dynsrc" || lowerKey == "background" || lowerKey == "lowsrc" {
  2136. if !isValidSrc(lowerVal) {
  2137. err = fmt.Errorf("invalid src attribute value: %s", attr.Val)
  2138. return err
  2139. }
  2140. }
  2141. if strings.HasPrefix(lowerKey, "on") {
  2142. err = fmt.Errorf("the event is forbidden: %s:%s", attr.Key, attr.Val)
  2143. return err
  2144. }
  2145. if lowerKey == "style" {
  2146. if strings.Contains(lowerVal, "javascript:") || strings.Contains(lowerVal, "script:") {
  2147. err = fmt.Errorf("invalid style attribute value: %s", attr.Val)
  2148. return err
  2149. }
  2150. }
  2151. }
  2152. /* case "src":
  2153. // 如果<src>是某个标签的属性,你可能需要递归检查其父节点
  2154. // 这里简单起见,我们假设<src>不是有效的HTML标签,并忽略它
  2155. // 在实际中,你可能需要更复杂的逻辑来处理这种情况
  2156. fmt.Println("Warning: Unexpected 'src' tag found.")*/
  2157. }
  2158. }
  2159. for c := n.FirstChild; c != nil; c = c.NextSibling {
  2160. if err = visit(c); err != nil {
  2161. return err
  2162. }
  2163. }
  2164. return nil
  2165. }
  2166. // 检查HTML文档中的事件
  2167. if err = visit(node); err != nil {
  2168. return
  2169. }
  2170. return
  2171. }
  2172. func ContentXssFilter(content string) (cleanContent string) {
  2173. p := customXssPolicy()
  2174. // The policy can then be used to sanitize lots of input and it is safe to use the policy in multiple goroutines
  2175. cleanContent = p.Sanitize(
  2176. content,
  2177. )
  2178. return
  2179. }
  2180. func customXssPolicy() (p *bluemonday.Policy) {
  2181. p = bluemonday.UGCPolicy()
  2182. // iframe
  2183. p.AllowElements("iframe")
  2184. p.AllowAttrs("width").OnElements("iframe")
  2185. p.AllowAttrs("height").OnElements("iframe")
  2186. p.AllowAttrs("src").OnElements("iframe")
  2187. p.AllowAttrs("frameborder").Matching(bluemonday.Number).OnElements("iframe")
  2188. p.AllowAttrs("allow").Matching(regexp.MustCompile(`[a-z; -]*`)).OnElements("iframe")
  2189. p.AllowAttrs("allowfullscreen").OnElements("iframe")
  2190. return
  2191. }
  2192. // SecondsToHHMMSS 秒转HH:MM:SS
  2193. func SecondsToHHMMSS(seconds int) string {
  2194. duration := time.Duration(seconds) * time.Second
  2195. hours := int(duration.Hours())
  2196. minutes := int(duration.Minutes()) % 60
  2197. seconds = int(duration.Seconds()) % 60
  2198. if hours > 0 {
  2199. return fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds)
  2200. } else {
  2201. return fmt.Sprintf("%02d:%02d", minutes, seconds)
  2202. }
  2203. }
  2204. // MillisecondsToHHMMSS 毫秒转HH:MM:SS
  2205. func MillisecondsToHHMMSS(ms int) string {
  2206. duration := time.Duration(ms) * time.Millisecond
  2207. hours := int(duration / (time.Hour))
  2208. minutes := int((duration % (time.Hour)) / time.Minute)
  2209. seconds := int((duration % time.Hour % time.Minute) / time.Second)
  2210. // 将整数小时、分钟和秒数转换为字符串,并添加冒号分隔符
  2211. hourStr := strconv.Itoa(hours)
  2212. minuteStr := strconv.Itoa(minutes)
  2213. secondStr := strconv.Itoa(seconds)
  2214. // 根据不足两位数的情况补零
  2215. if len(hourStr) == 1 {
  2216. hourStr = "0" + hourStr
  2217. }
  2218. if len(minuteStr) == 1 {
  2219. minuteStr = "0" + minuteStr
  2220. }
  2221. if len(secondStr) == 1 {
  2222. secondStr = "0" + secondStr
  2223. }
  2224. return hourStr + ":" + minuteStr + ":" + secondStr
  2225. }
  2226. func ByteToMB(byteCount int) float64 {
  2227. return float64(byteCount) / (1024 * 1024)
  2228. }
  2229. // DateConvMysqlConvMongo
  2230. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  2231. // @author: Roc
  2232. // @datetime 2024-05-08 11:03:26
  2233. // @param dateCon string
  2234. func DateConvMysqlConvMongo(dateCon string) string {
  2235. cond := ""
  2236. switch dateCon {
  2237. case "=":
  2238. cond = "$eq"
  2239. case "<":
  2240. cond = "$lt"
  2241. case "<=":
  2242. cond = "$lte"
  2243. case ">":
  2244. cond = "$gt"
  2245. case ">=":
  2246. cond = "$gte"
  2247. }
  2248. return cond
  2249. }