common.go 79 KB

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