common.go 57 KB

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