common.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/md5"
  7. "crypto/sha1"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "image"
  14. "image/png"
  15. "io"
  16. "math"
  17. "math/rand"
  18. "net"
  19. "net/http"
  20. "os"
  21. "os/exec"
  22. "path"
  23. "regexp"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/shopspring/decimal"
  28. "gorm.io/gorm"
  29. )
  30. // 随机数种子
  31. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  32. func GetRandString(size int) string {
  33. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  34. randomSb := ""
  35. digitSize := len(allLetterDigit)
  36. for i := 0; i < size; i++ {
  37. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  38. }
  39. return randomSb
  40. }
  41. func GetRandStringNoSpecialChar(size int) string {
  42. 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"}
  43. randomSb := ""
  44. digitSize := len(allLetterDigit)
  45. for i := 0; i < size; i++ {
  46. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  47. }
  48. return randomSb
  49. }
  50. func StringsToJSON(str string) string {
  51. rs := []rune(str)
  52. jsons := ""
  53. for _, r := range rs {
  54. rint := int(r)
  55. if rint < 128 {
  56. jsons += string(r)
  57. } else {
  58. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  59. }
  60. }
  61. return jsons
  62. }
  63. // 序列化
  64. func ToString(v interface{}) string {
  65. data, _ := json.Marshal(v)
  66. return string(data)
  67. }
  68. // md5加密
  69. func MD5(data string) string {
  70. m := md5.Sum([]byte(data))
  71. return hex.EncodeToString(m[:])
  72. }
  73. // 获取数字随机字符
  74. func GetRandDigit(n int) string {
  75. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  76. }
  77. // 获取随机数
  78. func GetRandNumber(n int) int {
  79. return rnd.Intn(n)
  80. }
  81. func GetRandInt(min, max int) int {
  82. if min >= max || min == 0 || max == 0 {
  83. return max
  84. }
  85. return rand.Intn(max-min) + min
  86. }
  87. func GetToday(format string) string {
  88. today := time.Now().Format(format)
  89. return today
  90. }
  91. // 获取今天剩余秒数
  92. func GetTodayLastSecond() time.Duration {
  93. today := GetToday(FormatDate) + " 23:59:59"
  94. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  95. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  96. }
  97. // 处理出生日期函数
  98. func GetBrithDate(idcard string) string {
  99. l := len(idcard)
  100. var s string
  101. if l == 15 {
  102. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  103. return s
  104. }
  105. if l == 18 {
  106. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  107. return s
  108. }
  109. return GetToday(FormatDate)
  110. }
  111. // 处理性别
  112. func WhichSexByIdcard(idcard string) string {
  113. var sexs = [2]string{"女", "男"}
  114. length := len(idcard)
  115. if length == 18 {
  116. sex, _ := strconv.Atoi(string(idcard[16]))
  117. return sexs[sex%2]
  118. } else if length == 15 {
  119. sex, _ := strconv.Atoi(string(idcard[14]))
  120. return sexs[sex%2]
  121. }
  122. return "男"
  123. }
  124. // 截取小数点后几位
  125. func SubFloatToString(f float64, m int) string {
  126. n := strconv.FormatFloat(f, 'f', -1, 64)
  127. if n == "" {
  128. return ""
  129. }
  130. if m >= len(n) {
  131. return n
  132. }
  133. newn := strings.Split(n, ".")
  134. if m == 0 {
  135. return newn[0]
  136. }
  137. if len(newn) < 2 || m >= len(newn[1]) {
  138. return n
  139. }
  140. return newn[0] + "." + newn[1][:m]
  141. }
  142. // 截取小数点后几位
  143. func SubFloatToFloat(f float64, m int) float64 {
  144. newn := SubFloatToString(f, m)
  145. newf, _ := strconv.ParseFloat(newn, 64)
  146. return newf
  147. }
  148. // 截取小数点后几位
  149. func SubFloatToFloatStr(f float64, m int) string {
  150. newn := SubFloatToString(f, m)
  151. return newn
  152. }
  153. // 获取相差时间-年
  154. func GetYearDiffer(start_time, end_time string) int {
  155. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  156. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  157. age := t2.Year() - t1.Year()
  158. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  159. age--
  160. }
  161. return age
  162. }
  163. // 获取相差时间-秒
  164. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  165. diff := end_time.Unix() - start_time.Unix()
  166. return diff
  167. }
  168. func FixFloat(f float64, m int) float64 {
  169. newn := SubFloatToString(f+0.00000001, m)
  170. newf, _ := strconv.ParseFloat(newn, 64)
  171. return newf
  172. }
  173. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  174. func StrListToString(strList []string) (str string) {
  175. if len(strList) > 0 {
  176. for k, v := range strList {
  177. if k == 0 {
  178. str = v
  179. } else {
  180. str = str + "," + v
  181. }
  182. }
  183. return
  184. }
  185. return ""
  186. }
  187. // 数据没有记录
  188. func ErrNoRow() string {
  189. return "<QuerySeter> no row found"
  190. }
  191. // IsErrNoRow
  192. // @Description: 判断是否是gorm的查询不到数据的报错
  193. // @param err
  194. // @return bool
  195. func IsErrNoRow(err error) bool {
  196. if err == nil {
  197. return false
  198. }
  199. return errors.Is(err, gorm.ErrRecordNotFound)
  200. }
  201. // 校验邮箱格式
  202. func ValidateEmailFormatat(email string) bool {
  203. reg := regexp.MustCompile(RegularEmail)
  204. return reg.MatchString(email)
  205. }
  206. // 验证是否是手机号
  207. func ValidateMobileFormatat(mobileNum string) bool {
  208. reg := regexp.MustCompile(RegularMobile)
  209. return reg.MatchString(mobileNum)
  210. }
  211. // 判断文件是否存在
  212. func FileIsExist(filePath string) bool {
  213. _, err := os.Stat(filePath)
  214. return err == nil || os.IsExist(err)
  215. }
  216. // 获取图片扩展名
  217. func GetImgExt(file string) (ext string, err error) {
  218. var headerByte []byte
  219. headerByte = make([]byte, 8)
  220. fd, err := os.Open(file)
  221. if err != nil {
  222. return "", err
  223. }
  224. defer fd.Close()
  225. _, err = fd.Read(headerByte)
  226. if err != nil {
  227. return "", err
  228. }
  229. xStr := fmt.Sprintf("%x", headerByte)
  230. switch {
  231. case xStr == "89504e470d0a1a0a":
  232. ext = ".png"
  233. case xStr == "0000010001002020":
  234. ext = ".ico"
  235. case xStr == "0000020001002020":
  236. ext = ".cur"
  237. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  238. ext = ".gif"
  239. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  240. ext = ".tga"
  241. case xStr[:8] == "464f524d":
  242. ext = ".iff"
  243. case xStr[:8] == "52494646":
  244. ext = ".ani"
  245. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  246. ext = ".tiff"
  247. case xStr[:4] == "424d":
  248. ext = ".bmp"
  249. case xStr[:4] == "ffd8":
  250. ext = ".jpg"
  251. case xStr[:2] == "0a":
  252. ext = ".pcx"
  253. default:
  254. ext = ""
  255. }
  256. return ext, nil
  257. }
  258. // 保存图片
  259. func SaveImage(path string, img image.Image) (err error) {
  260. //需要保持的文件
  261. imgfile, err := os.Create(path)
  262. defer imgfile.Close()
  263. // 以PNG格式保存文件
  264. err = png.Encode(imgfile, img)
  265. return err
  266. }
  267. // 下载图片
  268. func DownloadImage(imgUrl string) (filePath string, err error) {
  269. imgPath := "./static/imgs/"
  270. fileName := path.Base(imgUrl)
  271. res, err := http.Get(imgUrl)
  272. if err != nil {
  273. fmt.Println("A error occurred!")
  274. return
  275. }
  276. defer res.Body.Close()
  277. // 获得get请求响应的reader对象
  278. reader := bufio.NewReaderSize(res.Body, 32*1024)
  279. filePath = imgPath + fileName
  280. file, err := os.Create(filePath)
  281. if err != nil {
  282. return
  283. }
  284. // 获得文件的writer对象
  285. writer := bufio.NewWriter(file)
  286. written, _ := io.Copy(writer, reader)
  287. fmt.Printf("Total length: %d \n", written)
  288. return
  289. }
  290. // 保存base64数据为文件
  291. func SaveBase64ToFile(content, path string) error {
  292. data, err := base64.StdEncoding.DecodeString(content)
  293. if err != nil {
  294. return err
  295. }
  296. f, err := os.Create(path)
  297. defer f.Close()
  298. if err != nil {
  299. return err
  300. }
  301. f.Write(data)
  302. return nil
  303. }
  304. func SaveBase64ToFileBySeek(content, path string) (err error) {
  305. data, err := base64.StdEncoding.DecodeString(content)
  306. exist, err := PathExists(path)
  307. if err != nil {
  308. return
  309. }
  310. if !exist {
  311. f, err := os.Create(path)
  312. if err != nil {
  313. return err
  314. }
  315. n, _ := f.Seek(0, 2)
  316. // 从末尾的偏移量开始写入内容
  317. _, err = f.WriteAt([]byte(data), n)
  318. defer f.Close()
  319. } else {
  320. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  321. if err != nil {
  322. return err
  323. }
  324. n, _ := f.Seek(0, 2)
  325. // 从末尾的偏移量开始写入内容
  326. _, err = f.WriteAt([]byte(data), n)
  327. defer f.Close()
  328. }
  329. return nil
  330. }
  331. func PathExists(path string) (bool, error) {
  332. _, err := os.Stat(path)
  333. if err == nil {
  334. return true, nil
  335. }
  336. if os.IsNotExist(err) {
  337. return false, nil
  338. }
  339. return false, err
  340. }
  341. func StartIndex(page, pagesize int) int {
  342. if page > 1 {
  343. return (page - 1) * pagesize
  344. }
  345. return 0
  346. }
  347. func PageCount(count, pagesize int) int {
  348. if count%pagesize > 0 {
  349. return count/pagesize + 1
  350. } else {
  351. return count / pagesize
  352. }
  353. }
  354. func TrimHtml(src string) string {
  355. //将HTML标签全转换成小写
  356. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  357. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  358. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  359. src = re.ReplaceAllString(src, "[图片]")
  360. re, _ = regexp.Compile("class[\\S\\s]+?>")
  361. src = re.ReplaceAllString(src, "")
  362. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  363. src = re.ReplaceAllString(src, "")
  364. return strings.TrimSpace(src)
  365. }
  366. //1556164246 -> 2019-04-25 03:50:46 +0000
  367. //timestamp
  368. func TimeToTimestamp() {
  369. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  370. }
  371. func ToUnicode(text string) string {
  372. textQuoted := strconv.QuoteToASCII(text)
  373. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  374. return textUnquoted
  375. }
  376. func VersionToInt(version string) int {
  377. version = strings.Replace(version, ".", "", -1)
  378. n, _ := strconv.Atoi(version)
  379. return n
  380. }
  381. func IsCheckInList(list []int, s int) bool {
  382. for _, v := range list {
  383. if v == s {
  384. return true
  385. }
  386. }
  387. return false
  388. }
  389. func round(num float64) int {
  390. return int(num + math.Copysign(0.5, num))
  391. }
  392. func toFixed(num float64, precision int) float64 {
  393. output := math.Pow(10, float64(precision))
  394. return float64(round(num*output)) / output
  395. }
  396. // GetWilsonScore returns Wilson Score
  397. func GetWilsonScore(p, n float64) float64 {
  398. if p == 0 && n == 0 {
  399. return 0
  400. }
  401. 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)
  402. }
  403. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  404. func ChangeWordsToNum(str string) (numStr string) {
  405. words := ([]rune)(str)
  406. num := 0
  407. n := 0
  408. for i := 0; i < len(words); i++ {
  409. word := string(words[i : i+1])
  410. switch word {
  411. case "万":
  412. if n == 0 {
  413. n = 1
  414. }
  415. n = n * 10000
  416. num = num*10000 + n
  417. n = 0
  418. case "千":
  419. if n == 0 {
  420. n = 1
  421. }
  422. n = n * 1000
  423. num += n
  424. n = 0
  425. case "百":
  426. if n == 0 {
  427. n = 1
  428. }
  429. n = n * 100
  430. num += n
  431. n = 0
  432. case "十":
  433. if n == 0 {
  434. n = 1
  435. }
  436. n = n * 10
  437. num += n
  438. n = 0
  439. case "一":
  440. n += 1
  441. case "二":
  442. n += 2
  443. case "三":
  444. n += 3
  445. case "四":
  446. n += 4
  447. case "五":
  448. n += 5
  449. case "六":
  450. n += 6
  451. case "七":
  452. n += 7
  453. case "八":
  454. n += 8
  455. case "九":
  456. n += 9
  457. case "零":
  458. default:
  459. if n > 0 {
  460. num += n
  461. n = 0
  462. }
  463. if num == 0 {
  464. numStr += word
  465. } else {
  466. numStr += strconv.Itoa(num) + word
  467. num = 0
  468. }
  469. }
  470. }
  471. if n > 0 {
  472. num += n
  473. n = 0
  474. }
  475. if num != 0 {
  476. numStr += strconv.Itoa(num)
  477. }
  478. return
  479. }
  480. func Sha1(data string) string {
  481. sha1 := sha1.New()
  482. sha1.Write([]byte(data))
  483. return hex.EncodeToString(sha1.Sum([]byte("")))
  484. }
  485. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  486. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  487. out, err := exec.Command("bash", "-c", cmd).Output()
  488. if err != nil {
  489. return
  490. }
  491. outTimes := string(out)
  492. fmt.Println("outTimes:", outTimes)
  493. if outTimes != "" {
  494. timeArr := strings.Split(outTimes, ":")
  495. h := timeArr[0]
  496. m := timeArr[1]
  497. s := timeArr[2]
  498. hInt, err := strconv.Atoi(h)
  499. if err != nil {
  500. return playSeconds, err
  501. }
  502. mInt, err := strconv.Atoi(m)
  503. if err != nil {
  504. return playSeconds, err
  505. }
  506. s = strings.Trim(s, " ")
  507. s = strings.Trim(s, "\n")
  508. sInt, err := strconv.ParseFloat(s, 64)
  509. if err != nil {
  510. return playSeconds, err
  511. }
  512. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  513. }
  514. return
  515. }
  516. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  517. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  518. tradeCode = strings.Trim(tradeCode, " ")
  519. tradeCodeInt, err := strconv.Atoi(tradeCode)
  520. if err != nil {
  521. return
  522. }
  523. tradeCodeInt = tradeCodeInt + 1
  524. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  525. return
  526. }
  527. // excel日期字段格式化 yyyy-mm-dd
  528. func ConvertToFormatDay(excelDaysString string) string {
  529. // 2006-01-02 距离 1900-01-01的天数
  530. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  531. curDiffDay := excelDaysString
  532. b, _ := strconv.Atoi(curDiffDay)
  533. // 获取excel的日期距离2006-01-02的天数
  534. realDiffDay := b - baseDiffDay
  535. //fmt.Println("realDiffDay:",realDiffDay)
  536. // 距离2006-01-02 秒数
  537. realDiffSecond := realDiffDay * 24 * 3600
  538. //fmt.Println("realDiffSecond:",realDiffSecond)
  539. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  540. baseOriginSecond := 1136185445
  541. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  542. return resultTime
  543. }
  544. func CheckPwd(pwd string) bool {
  545. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  546. reg := regexp.MustCompile(compile)
  547. flag := reg.MatchString(pwd)
  548. return flag
  549. }
  550. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  551. // 数字月份必须前置补零
  552. if len(myMonth) == 1 {
  553. myMonth = "0" + myMonth
  554. }
  555. yInt, _ := strconv.Atoi(myYear)
  556. timeLayout := "2006-01-02 15:04:05"
  557. loc, _ := time.LoadLocation("Local")
  558. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  559. newMonth := theTime.Month()
  560. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  561. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  562. return t1, t2
  563. }
  564. // 移除字符串中的空格
  565. func TrimStr(str string) (str2 string) {
  566. return strings.Replace(str, " ", "", -1)
  567. }
  568. // 字符串转换为time
  569. func StrTimeToTime(strTime string) time.Time {
  570. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  571. loc, _ := time.LoadLocation("Local") //重要:获取时区
  572. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  573. return resultTime
  574. }
  575. // GetOrmInReplace 获取orm的in查询替换?的方法
  576. func GetOrmInReplace(num int) string {
  577. template := make([]string, num)
  578. for i := 0; i < num; i++ {
  579. template[i] = "?"
  580. }
  581. return strings.Join(template, ",")
  582. }
  583. // GetGormInReplace 获取orm的in查询替换?的方法
  584. func GetGormInReplace(num int) string {
  585. // 适配gorm, 直接强制返回一个?
  586. if num == 0 {
  587. return ""
  588. }
  589. return "?"
  590. }
  591. // RevSlice 反转切片
  592. func RevSlice(slice []int) []int {
  593. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  594. slice[i], slice[j] = slice[j], slice[i]
  595. }
  596. return slice
  597. }
  598. // GetTimeSubDay 计算两个时间的自然日期差
  599. func GetTimeSubDay(t1, t2 time.Time) int {
  600. var day int
  601. swap := false
  602. if t1.Unix() > t2.Unix() {
  603. t1, t2 = t2, t1
  604. swap = true
  605. }
  606. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  607. day = int(t2.Sub(t1).Hours() / 24)
  608. // 计算在t1+两个时间的余数之后天数是否有变化
  609. if t1_.Day() != t1.Day() {
  610. day += 1
  611. }
  612. if swap {
  613. day = -day
  614. }
  615. return day
  616. }
  617. // GetDaysBetween2Date 计算两个日期之间相差几天
  618. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  619. // 将字符串转化为Time格式
  620. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  621. if err != nil {
  622. return 0, err
  623. }
  624. // 将字符串转化为Time格式
  625. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  626. if err != nil {
  627. return 0, err
  628. }
  629. //计算相差天数
  630. return int(date1.Sub(date2).Hours() / 24), nil
  631. }
  632. // MapSorter 对于map 排序
  633. type MapSorter []Item
  634. type Item struct {
  635. Key int
  636. Val float64
  637. }
  638. func NewMapSorter(m map[int]float64) MapSorter {
  639. ms := make(MapSorter, 0, len(m))
  640. for k, v := range m {
  641. ms = append(ms, Item{k, v})
  642. }
  643. return ms
  644. }
  645. func (ms MapSorter) Len() int {
  646. return len(ms)
  647. }
  648. func (ms MapSorter) Less(i, j int) bool {
  649. return ms[i].Val > ms[j].Val // 按值排序
  650. //return ms[i].Key < ms[j].Key // 按键排序
  651. }
  652. func (ms MapSorter) Swap(i, j int) {
  653. ms[i], ms[j] = ms[j], ms[i]
  654. }
  655. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  656. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  657. for _, id := range idIntList {
  658. if id == searchId {
  659. has = true
  660. return
  661. }
  662. }
  663. return
  664. }
  665. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  666. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  667. for _, id := range idStrList {
  668. if id == searchId {
  669. has = true
  670. return
  671. }
  672. }
  673. return
  674. }
  675. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  676. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  677. startDate = tmpStartDate
  678. endDate = tmpEndDate
  679. switch dateType {
  680. case 1:
  681. startDate = "2000-01-01"
  682. endDate = ""
  683. case 2:
  684. startDate = "2010-01-01"
  685. endDate = ""
  686. case 3:
  687. startDate = "2015-01-01"
  688. endDate = ""
  689. case 4:
  690. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  691. startDate = "2021-01-01"
  692. endDate = ""
  693. case 5:
  694. //startDate = startDate + "-01"
  695. //endDate = endDate + "-01"
  696. case 6:
  697. //startDate = startDate + "-01"
  698. endDate = ""
  699. case 7:
  700. startDate = "2018-01-01"
  701. endDate = ""
  702. case 8:
  703. startDate = "2019-01-01"
  704. endDate = ""
  705. case 9:
  706. startDate = "2020-01-01"
  707. endDate = ""
  708. case 11:
  709. startDate = "2022-01-01"
  710. endDate = ""
  711. }
  712. // 兼容日期错误
  713. {
  714. if strings.Count(startDate, "-") == 1 {
  715. startDate = startDate + "-01"
  716. }
  717. if strings.Count(endDate, "-") == 1 {
  718. endDate = endDate + "-01"
  719. }
  720. }
  721. return
  722. }
  723. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  724. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  725. switch dateType {
  726. case 1:
  727. startDate = currDate.AddDate(0, -3, 0)
  728. case 2:
  729. startDate = currDate.AddDate(0, -6, 0)
  730. case 3:
  731. startDate = currDate.AddDate(-1, 0, 0)
  732. case 4:
  733. startDate = currDate.AddDate(-2, 0, 0)
  734. case 5:
  735. startDate = currDate.AddDate(-3, 0, 0)
  736. case 6:
  737. startDate = currDate.AddDate(-5, 0, 0)
  738. case 7:
  739. startDate = currDate.AddDate(-10, 0, 0)
  740. }
  741. return
  742. }
  743. // GetCeilNewNum 保留n位有效数字的向上取整
  744. // @params num 实际数据
  745. // @params baseLen 需要保留的有效位数
  746. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  747. if num >= 1 {
  748. tmpNum := int(math.Ceil(num)) // 向上取整
  749. str := strconv.Itoa(tmpNum)
  750. lenStr := len(str)
  751. if lenStr > baseLen {
  752. newNumStr := str[0:baseLen]
  753. newNumInt, _ := strconv.Atoi(newNumStr)
  754. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  755. if newNum < num {
  756. newNumInt += 1
  757. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  758. }
  759. } else {
  760. newNum = float64(tmpNum)
  761. }
  762. return
  763. } else if num > 0 {
  764. // 这是小数
  765. str := strconv.FormatFloat(num, 'f', -1, 64)
  766. // 去除小数点和负号
  767. str = removeDecimalPoint(str)
  768. // 计算字符串长度
  769. lenStr := len(str)
  770. if lenStr > baseLen {
  771. newNumStr := str[0:baseLen]
  772. newNumInt, _ := strconv.Atoi(newNumStr)
  773. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  774. if newNum < num {
  775. newNumInt += 1
  776. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  777. }
  778. } else {
  779. newNum = num
  780. }
  781. } else if num > -1 {
  782. // 这是小数
  783. str := strconv.FormatFloat(num, 'f', -1, 64)
  784. // 去除小数点和负号
  785. str = removeDecimalPoint(str)
  786. // 计算字符串长度
  787. lenStr := len(str)
  788. if lenStr > baseLen {
  789. newNumStr := str[0:baseLen]
  790. newNumInt, _ := strconv.Atoi(newNumStr)
  791. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  792. newNum = -newNum
  793. if newNum < num {
  794. newNumInt -= 1
  795. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  796. newNum = -newNum
  797. }
  798. } else {
  799. newNum = num
  800. }
  801. if newNum == -0 {
  802. newNum = 0
  803. }
  804. } else { // 小于等于-1
  805. tmpNumFloat := math.Abs(num)
  806. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  807. str := strconv.Itoa(tmpNum)
  808. lenStr := len(str)
  809. if lenStr > baseLen {
  810. newNumStr := str[0:baseLen]
  811. //fmt.Println("newNumStr:", newNumStr)
  812. newNumInt, _ := strconv.Atoi(newNumStr)
  813. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  814. newNum = -newNum
  815. if newNum < num {
  816. newNumInt -= 1
  817. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  818. newNum = -newNum
  819. }
  820. } else {
  821. newNum = float64(-tmpNum)
  822. }
  823. }
  824. return
  825. }
  826. // GetFloorNewNum 保留n位有效数字的向下取整
  827. // @params num 实际数据
  828. // @params baseLen 需要保留的有效位数
  829. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  830. if num >= 1 {
  831. tmpNum := int(math.Floor(num)) // 向上取整
  832. str := strconv.Itoa(tmpNum)
  833. lenStr := len(str)
  834. if lenStr > baseLen {
  835. newNumStr := str[0:baseLen]
  836. newNumInt, _ := strconv.Atoi(newNumStr)
  837. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  838. if newNum < num {
  839. newNumInt -= 1
  840. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  841. }
  842. } else {
  843. newNum = float64(tmpNum)
  844. }
  845. return
  846. } else if num > 0 {
  847. // 这是小数
  848. str := strconv.FormatFloat(num, 'f', -1, 64)
  849. // 去除小数点和负号
  850. str = removeDecimalPoint(str)
  851. // 计算字符串长度
  852. lenStr := len(str)
  853. if lenStr > baseLen {
  854. newNumStr := str[0:baseLen]
  855. newNumInt, _ := strconv.Atoi(newNumStr)
  856. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  857. if newNum > num {
  858. newNumInt -= 1
  859. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  860. }
  861. } else {
  862. newNum = num
  863. }
  864. } else if num > -1 {
  865. // 这是小数
  866. str := strconv.FormatFloat(num, 'f', -1, 64)
  867. // 去除小数点和负号
  868. str = removeDecimalPoint(str)
  869. // 计算字符串长度
  870. lenStr := len(str)
  871. if lenStr > baseLen {
  872. newNumStr := str[0:baseLen]
  873. newNumInt, _ := strconv.Atoi(newNumStr)
  874. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  875. newNum = -newNum
  876. if newNum > num {
  877. newNumInt += 1
  878. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  879. newNum = -newNum
  880. }
  881. } else {
  882. newNum = num
  883. }
  884. if newNum == -0 {
  885. newNum = 0
  886. }
  887. } else { // 小于等于-1
  888. tmpNumFloat := math.Abs(num)
  889. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  890. str := strconv.Itoa(tmpNum)
  891. lenStr := len(str)
  892. if lenStr > baseLen {
  893. newNumStr := str[0:baseLen]
  894. //fmt.Println("newNumStr:", newNumStr)
  895. newNumInt, _ := strconv.Atoi(newNumStr)
  896. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  897. newNum = -newNum
  898. if newNum > num {
  899. newNumInt += 1
  900. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  901. newNum = -newNum
  902. }
  903. } else {
  904. newNum = float64(-tmpNum)
  905. }
  906. }
  907. return
  908. }
  909. // 去除小数点和负号
  910. func removeDecimalPoint(str string) string {
  911. // 去除小数点
  912. str = str[strings.Index(str, ".")+1:]
  913. return str
  914. }
  915. func GetLocalIP() (ip string, err error) {
  916. addrs, err := net.InterfaceAddrs()
  917. if err != nil {
  918. return
  919. }
  920. for _, addr := range addrs {
  921. ipAddr, ok := addr.(*net.IPNet)
  922. if !ok {
  923. continue
  924. }
  925. if ipAddr.IP.IsLoopback() {
  926. continue
  927. }
  928. if !ipAddr.IP.IsGlobalUnicast() {
  929. continue
  930. }
  931. return ipAddr.IP.String(), nil
  932. }
  933. return
  934. }
  935. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
  936. startDate = tmpStartDate
  937. endDate = tmpEndDate
  938. switch dateType {
  939. case 1:
  940. startDate = "2000-01-01"
  941. endDate = ""
  942. case 2:
  943. startDate = "2010-01-01"
  944. endDate = ""
  945. case 3:
  946. startDate = "2015-01-01"
  947. endDate = ""
  948. case 4:
  949. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  950. startDate = "2021-01-01"
  951. endDate = ""
  952. case 5:
  953. //startDate = startDate + "-01"
  954. //endDate = endDate + "-01"
  955. case 6:
  956. //startDate = startDate + "-01"
  957. endDate = ""
  958. case 7:
  959. startDate = "2018-01-01"
  960. endDate = ""
  961. case 8:
  962. startDate = "2019-01-01"
  963. endDate = ""
  964. case 9:
  965. startDate = "2020-01-01"
  966. endDate = ""
  967. case 11:
  968. startDate = "2022-01-01"
  969. endDate = ""
  970. case DateTypeNYears:
  971. if startYear == 0 { //默认取最近5年
  972. startYear = 5
  973. }
  974. if yearMax == 0 {
  975. return
  976. }
  977. startYear = startYear - 1
  978. baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
  979. startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  980. endDate = ""
  981. }
  982. // 兼容日期错误
  983. {
  984. if strings.Count(startDate, "-") == 1 {
  985. startDate = startDate + "-01"
  986. }
  987. if strings.Count(endDate, "-") == 1 {
  988. endDate = endDate + "-01"
  989. }
  990. }
  991. return
  992. }
  993. func GetColorMap() map[int]string {
  994. colorMap := make(map[int]string)
  995. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  996. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  997. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  998. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  999. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  1000. for k, v := range colors {
  1001. colorMap[k] = v
  1002. }
  1003. return colorMap
  1004. }
  1005. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  1006. func GetDaysDiff1900(date string) int {
  1007. // 将字符串转换为时间类型
  1008. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  1009. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  1010. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  1011. if err != nil {
  1012. return 0
  1013. }
  1014. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  1015. if err != nil {
  1016. return 0
  1017. }
  1018. // 计算两个日期之间的天数差值
  1019. duration := tEnd.Sub(tStart).Hours() / 24
  1020. days := int(duration)
  1021. return days
  1022. }
  1023. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  1024. funMap := getFormulaMap()
  1025. for k, v := range funMap {
  1026. formulaStr = strings.Replace(formulaStr, k, v, -1)
  1027. }
  1028. replaceCount := 0
  1029. for tag, val := range valTagMap {
  1030. dvStr := fmt.Sprintf("%v", val)
  1031. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  1032. replaceCount++
  1033. }
  1034. for k, v := range funMap {
  1035. formulaStr = strings.Replace(formulaStr, v, k, -1)
  1036. }
  1037. return formulaStr
  1038. }
  1039. // GetFrequencyEn 获取频度的英文版
  1040. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1041. switch frequency {
  1042. case "日度":
  1043. frequencyEn = "day"
  1044. return
  1045. case "周度":
  1046. frequencyEn = "week"
  1047. return
  1048. case "旬度":
  1049. frequencyEn = "ten days"
  1050. return
  1051. case "月度":
  1052. frequencyEn = "month"
  1053. return
  1054. case "季度":
  1055. frequencyEn = "quarter"
  1056. return
  1057. case "年度":
  1058. frequencyEn = "year"
  1059. return
  1060. }
  1061. return
  1062. }
  1063. // DateConvMysqlConvMongo
  1064. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1065. // @author: Roc
  1066. // @datetime 2024-05-08 11:03:26
  1067. // @param dateCon string
  1068. func DateConvMysqlConvMongo(dateCon string) string {
  1069. cond := ""
  1070. switch dateCon {
  1071. case "=":
  1072. cond = "$eq"
  1073. case "<":
  1074. cond = "$lt"
  1075. case "<=":
  1076. cond = "$lte"
  1077. case ">":
  1078. cond = "$gt"
  1079. case ">=":
  1080. cond = "$gte"
  1081. }
  1082. return cond
  1083. }
  1084. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  1085. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  1086. remain := len(result) % 8
  1087. if remain > 0 {
  1088. mod := 8 - remain
  1089. for i := 0; i < mod; i++ {
  1090. result = append(result, 0)
  1091. }
  1092. }
  1093. origData, err := TripleDesDecrypt(result, []byte(desKey))
  1094. if err != nil {
  1095. panic(any(err))
  1096. }
  1097. return origData
  1098. }
  1099. // // 3DES解密
  1100. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  1101. block, err := des.NewTripleDESCipher(key)
  1102. if err != nil {
  1103. return nil, err
  1104. }
  1105. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  1106. origData := make([]byte, len(crypted))
  1107. // origData := crypted
  1108. blockMode.CryptBlocks(origData, crypted)
  1109. origData = PKCS5UnPadding(origData)
  1110. // origData = ZeroUnPadding(origData)
  1111. return origData, nil
  1112. }
  1113. func PKCS5UnPadding(origData []byte) []byte {
  1114. length := len(origData)
  1115. // 去掉最后一个字节 unpadding 次
  1116. unpadding := int(origData[length-1])
  1117. return origData[:(length - unpadding)]
  1118. }
  1119. func TimeTransferString(format string, t time.Time) string {
  1120. str := t.Format(format)
  1121. if t.IsZero() {
  1122. return ""
  1123. }
  1124. return str
  1125. }
  1126. // handleSystemAppointDateT
  1127. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1128. // @author: Roc
  1129. // @datetime2023-10-27 09:31:35
  1130. // @param Frequency string
  1131. // @param Day string
  1132. // @return date string
  1133. // @return err error
  1134. // @return errMsg string
  1135. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1136. //currDate := time.Now()
  1137. switch frequency {
  1138. case "本周":
  1139. day := int(currDate.Weekday())
  1140. if day == 0 { // 周日
  1141. day = 7
  1142. }
  1143. num := 0
  1144. switch appointDay {
  1145. case "周一":
  1146. num = 1
  1147. case "周二":
  1148. num = 2
  1149. case "周三":
  1150. num = 3
  1151. case "周四":
  1152. num = 4
  1153. case "周五":
  1154. num = 5
  1155. case "周六":
  1156. num = 6
  1157. case "周日":
  1158. num = 7
  1159. }
  1160. day = num - day
  1161. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1162. case "本旬":
  1163. day := currDate.Day()
  1164. var tmpDate time.Time
  1165. switch appointDay {
  1166. case "第一天":
  1167. if day <= 10 {
  1168. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1169. } else if day <= 20 {
  1170. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1171. } else {
  1172. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1173. }
  1174. case "最后一天":
  1175. if day <= 10 {
  1176. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1177. } else if day <= 20 {
  1178. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1179. } else {
  1180. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1181. }
  1182. }
  1183. date = tmpDate.Format(FormatDate)
  1184. case "本月":
  1185. var tmpDate time.Time
  1186. switch appointDay {
  1187. case "第一天":
  1188. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1189. case "最后一天":
  1190. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1191. }
  1192. date = tmpDate.Format(FormatDate)
  1193. case "本季":
  1194. month := currDate.Month()
  1195. var tmpDate time.Time
  1196. switch appointDay {
  1197. case "第一天":
  1198. if month <= 3 {
  1199. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1200. } else if month <= 6 {
  1201. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1202. } else if month <= 9 {
  1203. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1204. } else {
  1205. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1206. }
  1207. case "最后一天":
  1208. if month <= 3 {
  1209. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1210. } else if month <= 6 {
  1211. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1212. } else if month <= 9 {
  1213. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1214. } else {
  1215. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1216. }
  1217. }
  1218. date = tmpDate.Format(FormatDate)
  1219. case "本半年":
  1220. month := currDate.Month()
  1221. var tmpDate time.Time
  1222. switch appointDay {
  1223. case "第一天":
  1224. if month <= 6 {
  1225. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1226. } else {
  1227. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1228. }
  1229. case "最后一天":
  1230. if month <= 6 {
  1231. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1232. } else {
  1233. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1234. }
  1235. }
  1236. date = tmpDate.Format(FormatDate)
  1237. case "本年":
  1238. var tmpDate time.Time
  1239. switch appointDay {
  1240. case "第一天":
  1241. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1242. case "最后一天":
  1243. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1244. }
  1245. date = tmpDate.Format(FormatDate)
  1246. default:
  1247. errMsg = "错误的日期频度:" + frequency
  1248. err = errors.New(errMsg)
  1249. return
  1250. }
  1251. return
  1252. }
  1253. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1254. switch op {
  1255. case "=":
  1256. return a == b
  1257. case ">":
  1258. return a > b
  1259. case ">=":
  1260. return a >= b
  1261. case "<=":
  1262. return a <= b
  1263. case "<":
  1264. return a < b
  1265. }
  1266. return false
  1267. }
  1268. // GormDateStrToDateTimeStr
  1269. // @Description: gorm日期字符串格式转正常显示的日期时间字符串
  1270. // @param originalString
  1271. // @return formatStr
  1272. func GormDateStrToDateTimeStr(originalString string) (formatStr string) {
  1273. formatStr = originalString
  1274. if !strings.Contains(originalString, "T") {
  1275. return
  1276. }
  1277. // 解析原始字符串
  1278. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1279. if err != nil {
  1280. fmt.Println("Error parsing time:", err)
  1281. return
  1282. }
  1283. // 重新格式化时间
  1284. formatStr = t.Format(FormatDateTime)
  1285. return
  1286. }
  1287. // GormDateStrToDateStr
  1288. // @Description: gorm日期字符串格式转正常显示的日期字符串
  1289. // @param originalString
  1290. // @return formatStr
  1291. func GormDateStrToDateStr(originalString string) (formatStr string) {
  1292. formatStr = originalString
  1293. if !strings.Contains(originalString, "T") {
  1294. return
  1295. }
  1296. // 解析原始字符串
  1297. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1298. if err != nil {
  1299. fmt.Println("Error parsing time:", err)
  1300. return
  1301. }
  1302. // 重新格式化时间
  1303. formatStr = t.Format(FormatDate)
  1304. return
  1305. }
  1306. // RoundNumber 保留小数位数
  1307. func RoundNumber(num string, decimalPlaces int, hasPercent bool) string {
  1308. numDecimal, _ := decimal.NewFromString(num)
  1309. if hasPercent {
  1310. numDecimal = numDecimal.Mul(decimal.NewFromInt(100))
  1311. }
  1312. numFloat, _ := numDecimal.Round(int32(decimalPlaces)).Float64()
  1313. numStr := strconv.FormatFloat(numFloat, 'f', decimalPlaces, 64)
  1314. if hasPercent {
  1315. numStr += "%"
  1316. }
  1317. return numStr
  1318. }