common.go 74 KB

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