common.go 56 KB

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