common.go 55 KB

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