common.go 61 KB

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