common.go 61 KB

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