common.go 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113
  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. // SubStr 截取字符串(中文)
  987. func SubStr(str string, subLen int) string {
  988. strRune := []rune(str)
  989. bodyRuneLen := len(strRune)
  990. if bodyRuneLen > subLen {
  991. bodyRuneLen = subLen
  992. }
  993. str = string(strRune[:bodyRuneLen])
  994. return str
  995. }
  996. // HideString 给字段加***(从字符串中间替换,少于需要替换的长度,那么就补全*的长度)
  997. // src 待*字符串
  998. // hideLen 需要加*的长度
  999. func HideString(src string, hideLen int) string {
  1000. if src == "" {
  1001. return src
  1002. }
  1003. str := []rune(src)
  1004. if hideLen == 0 {
  1005. hideLen = 4
  1006. }
  1007. hideStr := ""
  1008. for i := 0; i < hideLen; i++ {
  1009. hideStr += "*"
  1010. }
  1011. strLen := len(str)
  1012. // 字符长度是1
  1013. if strLen == 1 {
  1014. return string(str[:1]) + hideStr
  1015. }
  1016. //字符长度大于1,但是小于等于需要隐藏的字符长度,那么就隐藏中间,保留前后各一位字符
  1017. if strLen <= hideLen+2 {
  1018. return string(str[:1]) + hideStr + string(str[strLen-1:])
  1019. }
  1020. subLen := strLen - hideLen //剩余需要展示的字符长度
  1021. decimal.NewFromFloat(2)
  1022. frontLenDecimal := decimal.NewFromInt(int64(subLen)).Div(decimal.NewFromInt(2)) //前面需要展示的字符的长度
  1023. frontLen := frontLenDecimal.Floor().IntPart()
  1024. return string(str[:frontLen]) + hideStr + string(str[frontLen+int64(hideLen):])
  1025. }
  1026. func GetLocalIP() (ip string, err error) {
  1027. addrs, err := net.InterfaceAddrs()
  1028. if err != nil {
  1029. return
  1030. }
  1031. for _, addr := range addrs {
  1032. ipAddr, ok := addr.(*net.IPNet)
  1033. if !ok {
  1034. continue
  1035. }
  1036. if ipAddr.IP.IsLoopback() {
  1037. continue
  1038. }
  1039. if !ipAddr.IP.IsGlobalUnicast() {
  1040. continue
  1041. }
  1042. return ipAddr.IP.String(), nil
  1043. }
  1044. return
  1045. }
  1046. // GetNowWeekMonday 获取上一周周一的时间
  1047. func GetPreWeekMonday() time.Time {
  1048. nowMonday := GetNowWeekMonday()
  1049. return nowMonday.AddDate(0, 0, -7)
  1050. }
  1051. // GetNowWeekLastDay 获取上一周最后一天的时间
  1052. func GetPreWeekLastDay() time.Time {
  1053. nowSunday := GetNowWeekLastDay()
  1054. return nowSunday.AddDate(0, 0, -7)
  1055. }
  1056. // GetNextWeekMonday 获取下一周周一的时间
  1057. func GetNextWeekMonday() time.Time {
  1058. nowMonday := GetNowWeekMonday()
  1059. return nowMonday.AddDate(0, 0, 7)
  1060. }
  1061. // GetNextWeekLastDay 获取下一周最后一天的时间
  1062. func GetNextWeekLastDay() time.Time {
  1063. nowSunday := GetNowWeekLastDay()
  1064. return nowSunday.AddDate(0, 0, 7)
  1065. }
  1066. // 处理真实姓名,隐藏中间的部分,如:张*,张*将
  1067. func DealRealName(realName string) string {
  1068. if realName == "" {
  1069. return ""
  1070. }
  1071. names := bytes.Runes([]byte(realName))
  1072. fistName := names[0]
  1073. length := len(names)
  1074. if length == 2 {
  1075. return string(fistName) + "*"
  1076. } else if length > 2 {
  1077. lastName := names[length-1]
  1078. return string(fistName) + "*" + string(lastName)
  1079. }
  1080. return realName
  1081. }
  1082. // Implode php中的implode(用来将int型的切片转为string)
  1083. func Implode(idIntList []int) (str string) {
  1084. for _, id := range idIntList {
  1085. str += fmt.Sprint(id, ",")
  1086. }
  1087. str = str[:len(str)-1]
  1088. return
  1089. }
  1090. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  1091. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  1092. for _, id := range idIntList {
  1093. if id == searchId {
  1094. has = true
  1095. return
  1096. }
  1097. }
  1098. return
  1099. }
  1100. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  1101. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  1102. for _, id := range idStrList {
  1103. if id == searchId {
  1104. has = true
  1105. return
  1106. }
  1107. }
  1108. return
  1109. }
  1110. // Intersection 求两个切片的交集
  1111. func Intersection(a []string, b []string) (inter []string) {
  1112. // interacting on the smallest list first can potentailly be faster...but not by much, worse case is the same
  1113. low, high := a, b
  1114. if len(a) > len(b) {
  1115. low = b
  1116. high = a
  1117. }
  1118. done := false
  1119. for i, l := range low {
  1120. for j, h := range high {
  1121. // get future index values
  1122. f1 := i + 1
  1123. f2 := j + 1
  1124. if l == h {
  1125. inter = append(inter, h)
  1126. if f1 < len(low) && f2 < len(high) {
  1127. // if the future values aren't the same then that's the end of the intersection
  1128. if low[f1] != high[f2] {
  1129. done = true
  1130. }
  1131. }
  1132. // 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
  1133. high = high[:j+copy(high[j:], high[j+1:])]
  1134. break
  1135. }
  1136. }
  1137. // nothing in the future so we are done
  1138. if done {
  1139. break
  1140. }
  1141. }
  1142. return
  1143. }
  1144. // Minus 获取差集
  1145. func Minus(a []string, b []string) []string {
  1146. //var inter []string
  1147. inter := make([]string, 0)
  1148. mp := make(map[string]bool)
  1149. for _, s := range a {
  1150. if _, ok := mp[s]; !ok {
  1151. mp[s] = true
  1152. }
  1153. }
  1154. for _, s := range b {
  1155. if _, ok := mp[s]; ok {
  1156. delete(mp, s)
  1157. }
  1158. }
  1159. for key := range mp {
  1160. inter = append(inter, key)
  1161. }
  1162. return inter
  1163. }
  1164. // IntArr2joinString []int转字符串
  1165. func IntArr2joinString(arr []int, sep string) string {
  1166. if len(arr) == 0 {
  1167. return ""
  1168. }
  1169. strArr := make([]string, 0)
  1170. for _, v := range arr {
  1171. strArr = append(strArr, strconv.Itoa(v))
  1172. }
  1173. return strings.Join(strArr, sep)
  1174. }
  1175. // GetOneMonthFirstDay 获取某月的第一天的时间
  1176. func GetOneMonthFirstDay(time2 time.Time) time.Time {
  1177. nowMonthFirstDay := time.Date(time2.Year(), time2.Month(), 1, 0, 0, 0, 0, time.Now().Location())
  1178. return nowMonthFirstDay
  1179. }
  1180. // GetOneMonthLastDay 获取某月最后一天的时间
  1181. func GetOneMonthLastDay(time2 time.Time) time.Time {
  1182. nowMonthLastDay := time.Date(time2.Year(), time2.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1183. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  1184. return nowMonthLastDay
  1185. }
  1186. func GetReportContentTextSub(content string) (contentSub string, err error) {
  1187. content = html.UnescapeString(content)
  1188. doc, err := goquery.NewDocumentFromReader(strings.NewReader(content))
  1189. docText := doc.Text()
  1190. bodyRune := []rune(docText)
  1191. bodyRuneLen := len(bodyRune)
  1192. if bodyRuneLen > 200 {
  1193. bodyRuneLen = 200
  1194. }
  1195. body := string(bodyRune[:bodyRuneLen])
  1196. contentSub = body
  1197. contentSub = strings.Replace(body, "Powered by Froala Editor", "", -1)
  1198. return
  1199. }
  1200. // GetOrmInReplace 获取orm的in查询替换?的方法
  1201. func GetOrmInReplace(num int) string {
  1202. template := make([]string, num)
  1203. for i := 0; i < num; i++ {
  1204. template[i] = "?"
  1205. }
  1206. return strings.Join(template, ",")
  1207. }
  1208. // RevSlice 反转切片
  1209. func RevSlice(slice []int) []int {
  1210. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  1211. slice[i], slice[j] = slice[j], slice[i]
  1212. }
  1213. return slice
  1214. }
  1215. // ReplaceSpaceAndWrap 去除空格跟换行
  1216. func ReplaceSpaceAndWrap(str string) string {
  1217. // 去除空格
  1218. str = strings.Replace(str, " ", "", -1)
  1219. // 去除换行符
  1220. str = strings.Replace(str, "\n", "", -1)
  1221. return str
  1222. }
  1223. // JoinStr2IntArr 拼接字符串转[]int
  1224. func JoinStr2IntArr(str, sep string) (arr []int) {
  1225. arr = make([]int, 0)
  1226. if str == "" {
  1227. return
  1228. }
  1229. if sep == "" {
  1230. sep = ","
  1231. }
  1232. strArr := strings.Split(str, sep)
  1233. if len(strArr) == 0 {
  1234. return
  1235. }
  1236. for i := range strArr {
  1237. v, e := strconv.Atoi(strArr[i])
  1238. // int2str此处过滤掉无效int
  1239. if e != nil {
  1240. continue
  1241. }
  1242. arr = append(arr, v)
  1243. }
  1244. return
  1245. }
  1246. // 字符串转换为time类型
  1247. func StrDateToDate(strTime string) time.Time {
  1248. timeLayout := "2006-01-02" //转化所需模板
  1249. loc, _ := time.LoadLocation("Local") //重要:获取时区
  1250. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  1251. return resultTime
  1252. }
  1253. // GetTimeSubDay 计算两个时间的自然日期差(后面减去前面)
  1254. func GetTimeSubDay(t1, t2 time.Time) int {
  1255. var day int
  1256. swap := false
  1257. if t1.Unix() > t2.Unix() {
  1258. t1, t2 = t2, t1
  1259. swap = true
  1260. }
  1261. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  1262. day = int(t2.Sub(t1).Hours() / 24)
  1263. // 计算在t1+两个时间的余数之后天数是否有变化
  1264. if t1_.Day() != t1.Day() {
  1265. day += 1
  1266. }
  1267. if swap {
  1268. day = -day
  1269. }
  1270. return day
  1271. }
  1272. // 去除非中文字符串
  1273. func StrFilterNonChinese(src *string) {
  1274. var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$")
  1275. strn := ""
  1276. for _, c := range *src {
  1277. if hzRegexp.MatchString(string(c)) {
  1278. strn += string(c)
  1279. }
  1280. }
  1281. *src = strn
  1282. }
  1283. // MinusInt 获取两个[]int差集
  1284. func MinusInt(a []int, b []int) []int {
  1285. var diff []int
  1286. mpA, mpB := make(map[int]bool), make(map[int]bool)
  1287. for _, v := range a {
  1288. mpA[v] = true
  1289. }
  1290. for _, v := range b {
  1291. mpB[v] = true
  1292. }
  1293. for _, s := range a {
  1294. if !mpB[s] {
  1295. diff = append(diff, s)
  1296. }
  1297. }
  1298. for _, s := range b {
  1299. if !mpA[s] {
  1300. diff = append(diff, s)
  1301. }
  1302. }
  1303. return diff
  1304. }
  1305. // IntersectInt 获取两个[]int交集
  1306. func IntersectInt(nums1 []int, nums2 []int) []int {
  1307. m := make(map[int]int)
  1308. var res []int
  1309. for _, num := range nums1 {
  1310. m[num]++
  1311. }
  1312. for _, num := range nums2 {
  1313. if m[num] > 0 {
  1314. res = append(res, num)
  1315. m[num]--
  1316. }
  1317. }
  1318. return res
  1319. }
  1320. // MapSorter 对于map 排序
  1321. type MapSorter []Item
  1322. type Item struct {
  1323. Key int
  1324. Val float64
  1325. }
  1326. func NewMapSorter(m map[int]float64) MapSorter {
  1327. ms := make(MapSorter, 0, len(m))
  1328. for k, v := range m {
  1329. ms = append(ms, Item{k, v})
  1330. }
  1331. return ms
  1332. }
  1333. func (ms MapSorter) Len() int {
  1334. return len(ms)
  1335. }
  1336. func (ms MapSorter) Less(i, j int) bool {
  1337. return ms[i].Val > ms[j].Val // 按值排序
  1338. //return ms[i].Key < ms[j].Key // 按键排序
  1339. }
  1340. func (ms MapSorter) Swap(i, j int) {
  1341. ms[i], ms[j] = ms[j], ms[i]
  1342. }
  1343. // FormatFileSize 字节的单位转换 保留两位小数
  1344. func FormatFileSize(fileSize int64) (size string) {
  1345. if fileSize < 1024 {
  1346. return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
  1347. } else if fileSize < (1024 * 1024) {
  1348. return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
  1349. } else if fileSize < (1024 * 1024 * 1024) {
  1350. return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
  1351. } else if fileSize < (1024 * 1024 * 1024 * 1024) {
  1352. return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
  1353. } else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
  1354. return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
  1355. } else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
  1356. return fmt.Sprintf("%.2fPB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
  1357. }
  1358. }
  1359. func GetDurationFormatBySecond(sec int) (formatString string) {
  1360. if sec == 0 {
  1361. formatString = "0分钟"
  1362. return
  1363. } else if sec <= 60 && sec > 0 {
  1364. formatString = "1分钟"
  1365. return
  1366. }
  1367. duration := time.Duration(int64(sec)) * time.Second
  1368. h := int(duration.Hours())
  1369. m := int(duration.Minutes()) % 60
  1370. //s := int(duration.Seconds()) % 60
  1371. if h > 0 {
  1372. formatString = fmt.Sprintf("%d小时", h)
  1373. }
  1374. if m > 0 {
  1375. formatString += fmt.Sprintf("%d分钟", m)
  1376. }
  1377. //if s > 0 {
  1378. // formatString += fmt.Sprintf("%d秒", s)
  1379. //}
  1380. return
  1381. }
  1382. // GetDaysBetween2Date 计算两个日期之间相差几天
  1383. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  1384. // 将字符串转化为Time格式
  1385. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  1386. if err != nil {
  1387. return 0, err
  1388. }
  1389. // 将字符串转化为Time格式
  1390. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  1391. if err != nil {
  1392. return 0, err
  1393. }
  1394. //计算相差天数
  1395. return int(date1.Sub(date2).Hours() / 24), nil
  1396. }
  1397. // GetFrequencyEn 获取频度的英文版
  1398. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1399. switch frequency {
  1400. case "日度":
  1401. frequencyEn = "day"
  1402. return
  1403. case "周度":
  1404. frequencyEn = "week"
  1405. return
  1406. case "旬度":
  1407. frequencyEn = "ten days"
  1408. return
  1409. case "月度":
  1410. frequencyEn = "month"
  1411. return
  1412. case "季度":
  1413. frequencyEn = "quarter"
  1414. return
  1415. case "年度":
  1416. frequencyEn = "year"
  1417. return
  1418. }
  1419. return
  1420. }
  1421. // GetLeadUnitEn 获取移动单位的英文版
  1422. func GetLeadUnitEn(unit string) (unitEn string) {
  1423. switch unit {
  1424. case "天":
  1425. unitEn = "day"
  1426. return
  1427. case "周":
  1428. unitEn = "week"
  1429. return
  1430. case "月":
  1431. unitEn = "month"
  1432. return
  1433. case "季":
  1434. unitEn = "quarter"
  1435. return
  1436. case "年":
  1437. unitEn = "year"
  1438. return
  1439. }
  1440. return
  1441. }
  1442. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  1443. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  1444. startDate = tmpStartDate
  1445. endDate = tmpEndDate
  1446. switch dateType {
  1447. case 1:
  1448. startDate = "2000-01-01"
  1449. endDate = ""
  1450. case 2:
  1451. startDate = "2010-01-01"
  1452. endDate = ""
  1453. case 3:
  1454. startDate = "2015-01-01"
  1455. endDate = ""
  1456. case 4:
  1457. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  1458. startDate = "2021-01-01"
  1459. endDate = ""
  1460. case 5:
  1461. //startDate = startDate + "-01"
  1462. //endDate = endDate + "-01"
  1463. case 6:
  1464. //startDate = startDate + "-01"
  1465. endDate = ""
  1466. case 7:
  1467. startDate = "2018-01-01"
  1468. endDate = ""
  1469. case 8:
  1470. startDate = "2019-01-01"
  1471. endDate = ""
  1472. case 9:
  1473. startDate = "2020-01-01"
  1474. endDate = ""
  1475. case 11:
  1476. startDate = "2022-01-01"
  1477. endDate = ""
  1478. }
  1479. // 兼容日期错误
  1480. {
  1481. if strings.Count(startDate, "-") == 1 {
  1482. startDate = startDate + "-01"
  1483. }
  1484. if strings.Count(endDate, "-") == 1 {
  1485. endDate = endDate + "-01"
  1486. }
  1487. }
  1488. return
  1489. }
  1490. func TimeTransferString(format string, t time.Time) string {
  1491. str := t.Format(format)
  1492. if t.IsZero() {
  1493. return ""
  1494. }
  1495. return str
  1496. }
  1497. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  1498. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  1499. switch dateType {
  1500. case 1:
  1501. startDate = currDate.AddDate(0, -3, 0)
  1502. case 2:
  1503. startDate = currDate.AddDate(0, -6, 0)
  1504. case 3:
  1505. startDate = currDate.AddDate(-1, 0, 0)
  1506. case 4:
  1507. startDate = currDate.AddDate(-2, 0, 0)
  1508. case 5:
  1509. startDate = currDate.AddDate(-3, 0, 0)
  1510. case 6:
  1511. startDate = currDate.AddDate(-5, 0, 0)
  1512. case 7:
  1513. startDate = currDate.AddDate(-10, 0, 0)
  1514. }
  1515. return
  1516. }
  1517. // GetCeilNewNum 保留n位有效数字的向上取整
  1518. // @params num 实际数据
  1519. // @params baseLen 需要保留的有效位数
  1520. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  1521. if num >= 1 {
  1522. tmpNum := int(math.Ceil(num)) // 向上取整
  1523. str := strconv.Itoa(tmpNum)
  1524. lenStr := len(str)
  1525. if lenStr > baseLen {
  1526. newNumStr := str[0:baseLen]
  1527. newNumInt, _ := strconv.Atoi(newNumStr)
  1528. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1529. if newNum < num {
  1530. newNumInt += 1
  1531. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1532. }
  1533. } else {
  1534. newNum = float64(tmpNum)
  1535. }
  1536. return
  1537. } else if num > 0 {
  1538. // 这是小数
  1539. str := strconv.FormatFloat(num, 'f', -1, 64)
  1540. // 去除小数点和负号
  1541. str = removeDecimalPoint(str)
  1542. // 计算字符串长度
  1543. lenStr := len(str)
  1544. if lenStr > baseLen {
  1545. newNumStr := str[0:baseLen]
  1546. newNumInt, _ := strconv.Atoi(newNumStr)
  1547. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1548. if newNum < num {
  1549. newNumInt += 1
  1550. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1551. }
  1552. } else {
  1553. newNum = num
  1554. }
  1555. } else if num > -1 {
  1556. // 这是小数
  1557. str := strconv.FormatFloat(num, 'f', -1, 64)
  1558. // 去除小数点和负号
  1559. str = removeDecimalPoint(str)
  1560. // 计算字符串长度
  1561. lenStr := len(str)
  1562. if lenStr > baseLen {
  1563. newNumStr := str[0:baseLen]
  1564. newNumInt, _ := strconv.Atoi(newNumStr)
  1565. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1566. newNum = -newNum
  1567. if newNum < num {
  1568. newNumInt -= 1
  1569. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1570. newNum = -newNum
  1571. }
  1572. } else {
  1573. newNum = num
  1574. }
  1575. if newNum == -0 {
  1576. newNum = 0
  1577. }
  1578. } else { // 小于等于-1
  1579. tmpNumFloat := math.Abs(num)
  1580. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  1581. str := strconv.Itoa(tmpNum)
  1582. lenStr := len(str)
  1583. if lenStr > baseLen {
  1584. newNumStr := str[0:baseLen]
  1585. //fmt.Println("newNumStr:", newNumStr)
  1586. newNumInt, _ := strconv.Atoi(newNumStr)
  1587. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1588. newNum = -newNum
  1589. if newNum < num {
  1590. newNumInt -= 1
  1591. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1592. newNum = -newNum
  1593. }
  1594. } else {
  1595. newNum = float64(-tmpNum)
  1596. }
  1597. }
  1598. return
  1599. }
  1600. // GetFloorNewNum 保留n位有效数字的向下取整
  1601. // @params num 实际数据
  1602. // @params baseLen 需要保留的有效位数
  1603. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  1604. if num >= 1 {
  1605. tmpNum := int(math.Floor(num)) // 向上取整
  1606. str := strconv.Itoa(tmpNum)
  1607. lenStr := len(str)
  1608. if lenStr > baseLen {
  1609. newNumStr := str[0:baseLen]
  1610. newNumInt, _ := strconv.Atoi(newNumStr)
  1611. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1612. if newNum < num {
  1613. newNumInt -= 1
  1614. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1615. }
  1616. } else {
  1617. newNum = float64(tmpNum)
  1618. }
  1619. return
  1620. } else if num > 0 {
  1621. // 这是小数
  1622. str := strconv.FormatFloat(num, 'f', -1, 64)
  1623. // 去除小数点和负号
  1624. str = removeDecimalPoint(str)
  1625. // 计算字符串长度
  1626. lenStr := len(str)
  1627. if lenStr > baseLen {
  1628. newNumStr := str[0:baseLen]
  1629. newNumInt, _ := strconv.Atoi(newNumStr)
  1630. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1631. if newNum > num {
  1632. newNumInt -= 1
  1633. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1634. }
  1635. } else {
  1636. newNum = num
  1637. }
  1638. } else if num > -1 {
  1639. // 这是小数
  1640. str := strconv.FormatFloat(num, 'f', -1, 64)
  1641. // 去除小数点和负号
  1642. str = removeDecimalPoint(str)
  1643. // 计算字符串长度
  1644. lenStr := len(str)
  1645. if lenStr > baseLen {
  1646. newNumStr := str[0:baseLen]
  1647. newNumInt, _ := strconv.Atoi(newNumStr)
  1648. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1649. newNum = -newNum
  1650. if newNum > num {
  1651. newNumInt += 1
  1652. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  1653. newNum = -newNum
  1654. }
  1655. } else {
  1656. newNum = num
  1657. }
  1658. if newNum == -0 {
  1659. newNum = 0
  1660. }
  1661. } else { // 小于等于-1
  1662. tmpNumFloat := math.Abs(num)
  1663. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  1664. str := strconv.Itoa(tmpNum)
  1665. lenStr := len(str)
  1666. if lenStr > baseLen {
  1667. newNumStr := str[0:baseLen]
  1668. //fmt.Println("newNumStr:", newNumStr)
  1669. newNumInt, _ := strconv.Atoi(newNumStr)
  1670. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1671. newNum = -newNum
  1672. if newNum > num {
  1673. newNumInt += 1
  1674. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  1675. newNum = -newNum
  1676. }
  1677. } else {
  1678. newNum = float64(-tmpNum)
  1679. }
  1680. }
  1681. return
  1682. }
  1683. // 去除小数点和负号
  1684. func removeDecimalPoint(str string) string {
  1685. // 去除小数点
  1686. str = str[strings.Index(str, ".")+1:]
  1687. return str
  1688. }
  1689. // GetPredictEdbDayListByEndDate 根据截止日期获取预测指标日期列表
  1690. func GetPredictEdbDayListByEndDate(startDate, endDate time.Time, frequency string) (dayList []time.Time) {
  1691. //if !utils.InArrayByStr([]string{"日度", "周度", "月度"}, frequency)
  1692. switch frequency {
  1693. case "日度":
  1694. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 1) {
  1695. //周六、日排除
  1696. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1697. continue
  1698. }
  1699. dayList = append(dayList, currDate)
  1700. }
  1701. case "周度":
  1702. //nextDate := startDate.AddDate(0, 0, 7)
  1703. for currDate := startDate.AddDate(0, 0, 7); currDate.Before(endDate) || currDate.Equal(endDate); currDate = currDate.AddDate(0, 0, 7) {
  1704. dayList = append(dayList, currDate)
  1705. }
  1706. case "旬度":
  1707. for currDate := startDate.AddDate(0, 0, 1); currDate.Before(endDate) || currDate.Equal(endDate); {
  1708. nextDate := currDate.AddDate(0, 0, 1)
  1709. //每个月的10号、20号、最后一天,那么就写入
  1710. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1711. dayList = append(dayList, currDate)
  1712. }
  1713. currDate = nextDate
  1714. }
  1715. case "月度":
  1716. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1717. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1718. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1719. dayList = append(dayList, currDate)
  1720. }
  1721. currDate = currDate.AddDate(0, 0, 1)
  1722. }
  1723. case "季度":
  1724. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1725. // 每月的最后一天
  1726. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1727. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1728. // 季度日期就写入,否则不写入
  1729. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1730. dayList = append(dayList, currDate)
  1731. }
  1732. }
  1733. currDate = currDate.AddDate(0, 0, 1)
  1734. }
  1735. case "半年度":
  1736. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1737. // 每月的最后一天
  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. // 半年度日期就写入,否则不写入
  1741. if currDate.Month() == 6 || currDate.Month() == 12 {
  1742. dayList = append(dayList, currDate)
  1743. }
  1744. }
  1745. currDate = currDate.AddDate(0, 0, 1)
  1746. }
  1747. case "年度":
  1748. for currDate := startDate; currDate.Before(endDate) || currDate.Equal(endDate); {
  1749. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1750. if !currDate.After(endDate) && !currDate.Equal(startDate) {
  1751. dayList = append(dayList, currDate)
  1752. }
  1753. }
  1754. }
  1755. return
  1756. }
  1757. // GetPredictEdbDayListByNum 根据期数获取预测指标日期列表
  1758. func GetPredictEdbDayListByNum(startDate time.Time, num int, frequency string) (dayList []time.Time) {
  1759. switch frequency {
  1760. case "日度":
  1761. for i := 1; i <= num; {
  1762. currDate := startDate.AddDate(0, 0, i)
  1763. //周六、日排除
  1764. if currDate.Weekday() == time.Sunday || currDate.Weekday() == time.Saturday {
  1765. continue
  1766. }
  1767. dayList = append(dayList, currDate)
  1768. i++
  1769. }
  1770. case "周度":
  1771. for i := 1; i <= num; {
  1772. dayList = append(dayList, startDate.AddDate(0, 0, i*7))
  1773. i++
  1774. }
  1775. case "旬度":
  1776. currDate := startDate
  1777. for i := 1; i <= num; {
  1778. nextDate := currDate.AddDate(0, 0, 1)
  1779. //每个月的10号、20号、最后一天,那么就写入
  1780. if nextDate.Day() == 11 || nextDate.Day() == 21 || nextDate.Day() == 1 {
  1781. dayList = append(dayList, currDate)
  1782. i++
  1783. }
  1784. currDate = nextDate
  1785. }
  1786. case "月度":
  1787. currDate := startDate
  1788. for i := 1; i <= num; {
  1789. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1790. if !currDate.Equal(startDate) {
  1791. dayList = append(dayList, currDate)
  1792. i++
  1793. }
  1794. currDate = currDate.AddDate(0, 0, 1)
  1795. }
  1796. case "季度":
  1797. currDate := startDate
  1798. for i := 1; i <= num; {
  1799. // 每月的最后一天
  1800. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1801. if !currDate.Equal(startDate) {
  1802. // 季度日期就写入,否则不写入
  1803. if currDate.Month() == 3 || currDate.Month() == 6 || currDate.Month() == 9 || currDate.Month() == 12 {
  1804. dayList = append(dayList, currDate)
  1805. i++
  1806. }
  1807. }
  1808. currDate = currDate.AddDate(0, 0, 1)
  1809. }
  1810. case "半年度":
  1811. currDate := startDate
  1812. for i := 1; i <= num; {
  1813. // 每月的最后一天
  1814. currDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  1815. if !currDate.Equal(startDate) {
  1816. // 半年度日期就写入,否则不写入
  1817. if currDate.Month() == 6 || currDate.Month() == 12 {
  1818. dayList = append(dayList, currDate)
  1819. i++
  1820. }
  1821. }
  1822. currDate = currDate.AddDate(0, 0, 1)
  1823. }
  1824. case "年度":
  1825. currDate := startDate
  1826. for i := 1; i <= num; {
  1827. currDate = time.Date(currDate.Year()+1, 12, 31, 0, 0, 0, 0, time.Now().Location())
  1828. if !currDate.Equal(startDate) {
  1829. dayList = append(dayList, currDate)
  1830. i++
  1831. }
  1832. }
  1833. }
  1834. return
  1835. }
  1836. // GetDiffDays 计算两个日期相差的天数
  1837. func GetDiffDays(t1, t2 time.Time) int {
  1838. t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
  1839. t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)
  1840. return int(t1.Sub(t2).Hours() / 24)
  1841. }
  1842. // FormatTableDataShowValue 格式化自定表格显示数据
  1843. func FormatTableDataShowValue(x float64) (res string) {
  1844. if x > 1 || x < -1 {
  1845. res = decimal.NewFromFloat(x).Round(2).String()
  1846. return
  1847. }
  1848. // 介于-1到1之间
  1849. xStr := strconv.FormatFloat(x, 'f', -10, 64)
  1850. // 使用 strings.Split 函数将小数拆分为整数部分和小数部分
  1851. xParts := strings.Split(xStr, ".")
  1852. if len(xParts) < 2 {
  1853. res = fmt.Sprint(x)
  1854. return
  1855. }
  1856. // 计算小数部分的长度,即小数点后面的位数
  1857. xDecimals := len(xParts[1])
  1858. if xDecimals > 2 {
  1859. parts := xParts[1]
  1860. // 小数点后小于等于两位, 直接拼接返回
  1861. partLen := len(xParts[1])
  1862. if partLen <= 2 {
  1863. res = xParts[0] + "." + parts
  1864. return
  1865. }
  1866. // 找出第一个有效数字, 算出n
  1867. one := 0
  1868. for k, p := range parts {
  1869. // 48->0
  1870. if p != 48 {
  1871. if one == 0 {
  1872. one = k + 1
  1873. }
  1874. }
  1875. }
  1876. n := partLen - one
  1877. if n >= 1 {
  1878. n -= 1
  1879. } else {
  1880. one -= 1
  1881. }
  1882. var partFloat float64
  1883. partInt, _ := strconv.Atoi(parts)
  1884. partFloat, _ = decimal.NewFromInt(int64(partInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(n)))).Float64()
  1885. partFloat = math.Round(partFloat)
  1886. partFloat, _ = decimal.NewFromFloat(partFloat).Div(decimal.NewFromFloat(math.Pow(10, float64(one+1)))).Float64()
  1887. resParts := strings.Split(fmt.Sprint(partFloat), ".")
  1888. resPart := ""
  1889. if len(resParts) > 1 {
  1890. resPart = resParts[1]
  1891. } else {
  1892. resPart = resParts[0]
  1893. }
  1894. res = xParts[0] + "." + resPart
  1895. }
  1896. if xDecimals < 2 {
  1897. xDecimalsStr := xParts[1]
  1898. x, _ = strconv.ParseFloat(xParts[0]+"."+xDecimalsStr, 64)
  1899. res = xParts[0] + "." + xDecimalsStr
  1900. }
  1901. return
  1902. }
  1903. // 校验字符是否包含字母
  1904. func CheckStrHaveLetter(checkString string) (checked bool) {
  1905. 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"}
  1906. for _, v := range allLetterDigit {
  1907. if strings.Contains(checkString, v) {
  1908. checked = true
  1909. return true
  1910. }
  1911. }
  1912. return
  1913. }
  1914. func ArticleHasImgUrl(body string) (hasImg bool, err error) {
  1915. r := strings.NewReader(string(body))
  1916. doc, err := goquery.NewDocumentFromReader(r)
  1917. if err != nil {
  1918. fmt.Println(err)
  1919. }
  1920. doc.Find("img").Each(func(i int, s *goquery.Selection) {
  1921. hasImg = true
  1922. })
  1923. return
  1924. }