common.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  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. "gorm.io/gorm"
  14. "image"
  15. "image/png"
  16. "io"
  17. "math"
  18. "math/rand"
  19. "net"
  20. "net/http"
  21. "os"
  22. "os/exec"
  23. "path"
  24. "regexp"
  25. "strconv"
  26. "strings"
  27. "time"
  28. "github.com/shopspring/decimal"
  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 "record not 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. return "?"
  583. }
  584. // RevSlice 反转切片
  585. func RevSlice(slice []int) []int {
  586. for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
  587. slice[i], slice[j] = slice[j], slice[i]
  588. }
  589. return slice
  590. }
  591. // GetTimeSubDay 计算两个时间的自然日期差
  592. func GetTimeSubDay(t1, t2 time.Time) int {
  593. var day int
  594. swap := false
  595. if t1.Unix() > t2.Unix() {
  596. t1, t2 = t2, t1
  597. swap = true
  598. }
  599. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  600. day = int(t2.Sub(t1).Hours() / 24)
  601. // 计算在t1+两个时间的余数之后天数是否有变化
  602. if t1_.Day() != t1.Day() {
  603. day += 1
  604. }
  605. if swap {
  606. day = -day
  607. }
  608. return day
  609. }
  610. // GetDaysBetween2Date 计算两个日期之间相差几天
  611. func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
  612. // 将字符串转化为Time格式
  613. date1, err := time.ParseInLocation(format, date1Str, time.Local)
  614. if err != nil {
  615. return 0, err
  616. }
  617. // 将字符串转化为Time格式
  618. date2, err := time.ParseInLocation(format, date2Str, time.Local)
  619. if err != nil {
  620. return 0, err
  621. }
  622. //计算相差天数
  623. return int(date1.Sub(date2).Hours() / 24), nil
  624. }
  625. // MapSorter 对于map 排序
  626. type MapSorter []Item
  627. type Item struct {
  628. Key int
  629. Val float64
  630. }
  631. func NewMapSorter(m map[int]float64) MapSorter {
  632. ms := make(MapSorter, 0, len(m))
  633. for k, v := range m {
  634. ms = append(ms, Item{k, v})
  635. }
  636. return ms
  637. }
  638. func (ms MapSorter) Len() int {
  639. return len(ms)
  640. }
  641. func (ms MapSorter) Less(i, j int) bool {
  642. return ms[i].Val > ms[j].Val // 按值排序
  643. //return ms[i].Key < ms[j].Key // 按键排序
  644. }
  645. func (ms MapSorter) Swap(i, j int) {
  646. ms[i], ms[j] = ms[j], ms[i]
  647. }
  648. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  649. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  650. for _, id := range idIntList {
  651. if id == searchId {
  652. has = true
  653. return
  654. }
  655. }
  656. return
  657. }
  658. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  659. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  660. for _, id := range idStrList {
  661. if id == searchId {
  662. has = true
  663. return
  664. }
  665. }
  666. return
  667. }
  668. // GetDateByDateType 通过dateType获取需要的开始/结束日期
  669. func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
  670. startDate = tmpStartDate
  671. endDate = tmpEndDate
  672. switch dateType {
  673. case 1:
  674. startDate = "2000-01-01"
  675. endDate = ""
  676. case 2:
  677. startDate = "2010-01-01"
  678. endDate = ""
  679. case 3:
  680. startDate = "2015-01-01"
  681. endDate = ""
  682. case 4:
  683. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  684. startDate = "2021-01-01"
  685. endDate = ""
  686. case 5:
  687. //startDate = startDate + "-01"
  688. //endDate = endDate + "-01"
  689. case 6:
  690. //startDate = startDate + "-01"
  691. endDate = ""
  692. case 7:
  693. startDate = "2018-01-01"
  694. endDate = ""
  695. case 8:
  696. startDate = "2019-01-01"
  697. endDate = ""
  698. case 9:
  699. startDate = "2020-01-01"
  700. endDate = ""
  701. case 11:
  702. startDate = "2022-01-01"
  703. endDate = ""
  704. }
  705. // 兼容日期错误
  706. {
  707. if strings.Count(startDate, "-") == 1 {
  708. startDate = startDate + "-01"
  709. }
  710. if strings.Count(endDate, "-") == 1 {
  711. endDate = endDate + "-01"
  712. }
  713. }
  714. return
  715. }
  716. // GetDateByDateType2 通过dateType获取需要的开始/结束日期(日期类型:1:最近3月;2:最近6月;3:最近1年;4:最近2年;5:最近3年;6:最近5年;7:最近10年,8:自定义时间)
  717. func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
  718. switch dateType {
  719. case 1:
  720. startDate = currDate.AddDate(0, -3, 0)
  721. case 2:
  722. startDate = currDate.AddDate(0, -6, 0)
  723. case 3:
  724. startDate = currDate.AddDate(-1, 0, 0)
  725. case 4:
  726. startDate = currDate.AddDate(-2, 0, 0)
  727. case 5:
  728. startDate = currDate.AddDate(-3, 0, 0)
  729. case 6:
  730. startDate = currDate.AddDate(-5, 0, 0)
  731. case 7:
  732. startDate = currDate.AddDate(-10, 0, 0)
  733. }
  734. return
  735. }
  736. // GetCeilNewNum 保留n位有效数字的向上取整
  737. // @params num 实际数据
  738. // @params baseLen 需要保留的有效位数
  739. func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
  740. if num >= 1 {
  741. tmpNum := int(math.Ceil(num)) // 向上取整
  742. str := strconv.Itoa(tmpNum)
  743. lenStr := len(str)
  744. if lenStr > baseLen {
  745. newNumStr := str[0:baseLen]
  746. newNumInt, _ := strconv.Atoi(newNumStr)
  747. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  748. if newNum < num {
  749. newNumInt += 1
  750. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  751. }
  752. } else {
  753. newNum = float64(tmpNum)
  754. }
  755. return
  756. } else if num > 0 {
  757. // 这是小数
  758. str := strconv.FormatFloat(num, 'f', -1, 64)
  759. // 去除小数点和负号
  760. str = removeDecimalPoint(str)
  761. // 计算字符串长度
  762. lenStr := len(str)
  763. if lenStr > baseLen {
  764. newNumStr := str[0:baseLen]
  765. newNumInt, _ := strconv.Atoi(newNumStr)
  766. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  767. if newNum < num {
  768. newNumInt += 1
  769. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  770. }
  771. } else {
  772. newNum = num
  773. }
  774. } else if num > -1 {
  775. // 这是小数
  776. str := strconv.FormatFloat(num, 'f', -1, 64)
  777. // 去除小数点和负号
  778. str = removeDecimalPoint(str)
  779. // 计算字符串长度
  780. lenStr := len(str)
  781. if lenStr > baseLen {
  782. newNumStr := str[0:baseLen]
  783. newNumInt, _ := strconv.Atoi(newNumStr)
  784. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  785. newNum = -newNum
  786. if newNum < num {
  787. newNumInt -= 1
  788. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  789. newNum = -newNum
  790. }
  791. } else {
  792. newNum = num
  793. }
  794. if newNum == -0 {
  795. newNum = 0
  796. }
  797. } else { // 小于等于-1
  798. tmpNumFloat := math.Abs(num)
  799. tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
  800. str := strconv.Itoa(tmpNum)
  801. lenStr := len(str)
  802. if lenStr > baseLen {
  803. newNumStr := str[0:baseLen]
  804. //fmt.Println("newNumStr:", newNumStr)
  805. newNumInt, _ := strconv.Atoi(newNumStr)
  806. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  807. newNum = -newNum
  808. if newNum < num {
  809. newNumInt -= 1
  810. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  811. newNum = -newNum
  812. }
  813. } else {
  814. newNum = float64(-tmpNum)
  815. }
  816. }
  817. return
  818. }
  819. // GetFloorNewNum 保留n位有效数字的向下取整
  820. // @params num 实际数据
  821. // @params baseLen 需要保留的有效位数
  822. func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
  823. if num >= 1 {
  824. tmpNum := int(math.Floor(num)) // 向上取整
  825. str := strconv.Itoa(tmpNum)
  826. lenStr := len(str)
  827. if lenStr > baseLen {
  828. newNumStr := str[0:baseLen]
  829. newNumInt, _ := strconv.Atoi(newNumStr)
  830. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  831. if newNum < num {
  832. newNumInt -= 1
  833. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  834. }
  835. } else {
  836. newNum = float64(tmpNum)
  837. }
  838. return
  839. } else if num > 0 {
  840. // 这是小数
  841. str := strconv.FormatFloat(num, 'f', -1, 64)
  842. // 去除小数点和负号
  843. str = removeDecimalPoint(str)
  844. // 计算字符串长度
  845. lenStr := len(str)
  846. if lenStr > baseLen {
  847. newNumStr := str[0:baseLen]
  848. newNumInt, _ := strconv.Atoi(newNumStr)
  849. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  850. if newNum > num {
  851. newNumInt -= 1
  852. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  853. }
  854. } else {
  855. newNum = num
  856. }
  857. } else if num > -1 {
  858. // 这是小数
  859. str := strconv.FormatFloat(num, 'f', -1, 64)
  860. // 去除小数点和负号
  861. str = removeDecimalPoint(str)
  862. // 计算字符串长度
  863. lenStr := len(str)
  864. if lenStr > baseLen {
  865. newNumStr := str[0:baseLen]
  866. newNumInt, _ := strconv.Atoi(newNumStr)
  867. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  868. newNum = -newNum
  869. if newNum > num {
  870. newNumInt += 1
  871. newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
  872. newNum = -newNum
  873. }
  874. } else {
  875. newNum = num
  876. }
  877. if newNum == -0 {
  878. newNum = 0
  879. }
  880. } else { // 小于等于-1
  881. tmpNumFloat := math.Abs(num)
  882. tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
  883. str := strconv.Itoa(tmpNum)
  884. lenStr := len(str)
  885. if lenStr > baseLen {
  886. newNumStr := str[0:baseLen]
  887. //fmt.Println("newNumStr:", newNumStr)
  888. newNumInt, _ := strconv.Atoi(newNumStr)
  889. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  890. newNum = -newNum
  891. if newNum > num {
  892. newNumInt += 1
  893. newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
  894. newNum = -newNum
  895. }
  896. } else {
  897. newNum = float64(-tmpNum)
  898. }
  899. }
  900. return
  901. }
  902. // 去除小数点和负号
  903. func removeDecimalPoint(str string) string {
  904. // 去除小数点
  905. str = str[strings.Index(str, ".")+1:]
  906. return str
  907. }
  908. func GetLocalIP() (ip string, err error) {
  909. addrs, err := net.InterfaceAddrs()
  910. if err != nil {
  911. return
  912. }
  913. for _, addr := range addrs {
  914. ipAddr, ok := addr.(*net.IPNet)
  915. if !ok {
  916. continue
  917. }
  918. if ipAddr.IP.IsLoopback() {
  919. continue
  920. }
  921. if !ipAddr.IP.IsGlobalUnicast() {
  922. continue
  923. }
  924. return ipAddr.IP.String(), nil
  925. }
  926. return
  927. }
  928. func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear int, latestDate time.Time) (startDate, endDate string) {
  929. startDate = tmpStartDate
  930. endDate = tmpEndDate
  931. switch dateType {
  932. case 1:
  933. startDate = "2000-01-01"
  934. endDate = ""
  935. case 2:
  936. startDate = "2010-01-01"
  937. endDate = ""
  938. case 3:
  939. startDate = "2015-01-01"
  940. endDate = ""
  941. case 4:
  942. //startDate = strconv.Itoa(time.Now().Year()) + "-01-01"
  943. startDate = "2021-01-01"
  944. endDate = ""
  945. case 5:
  946. //startDate = startDate + "-01"
  947. //endDate = endDate + "-01"
  948. case 6:
  949. //startDate = startDate + "-01"
  950. endDate = ""
  951. case 7:
  952. startDate = "2018-01-01"
  953. endDate = ""
  954. case 8:
  955. startDate = "2019-01-01"
  956. endDate = ""
  957. case 9:
  958. startDate = "2020-01-01"
  959. endDate = ""
  960. case 11:
  961. startDate = "2022-01-01"
  962. endDate = ""
  963. case 12:
  964. startDate = "2023-01-01"
  965. endDate = ""
  966. case 13:
  967. startDate = "2024-01-01"
  968. endDate = ""
  969. case DateTypeNYears:
  970. if startYear == 0 { //默认取最近5年
  971. startYear = 5
  972. }
  973. if latestDate.IsZero() {
  974. return
  975. }
  976. startDate = latestDate.AddDate(-startYear, 0, 0).Format(FormatDate)
  977. endDate = ""
  978. }
  979. // 兼容日期错误
  980. {
  981. if strings.Count(startDate, "-") == 1 {
  982. startDate = startDate + "-01"
  983. }
  984. if strings.Count(endDate, "-") == 1 {
  985. endTime, err := time.Parse(FormatYearMonthDate, endDate)
  986. if err != nil {
  987. return
  988. }
  989. endDate = endTime.AddDate(0, 1, -1).Format(FormatDate)
  990. }
  991. }
  992. return
  993. }
  994. func GetColorMap() map[int]string {
  995. colorMap := make(map[int]string)
  996. colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
  997. "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
  998. "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
  999. "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
  1000. "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
  1001. for k, v := range colors {
  1002. colorMap[k] = v
  1003. }
  1004. return colorMap
  1005. }
  1006. // GetDaysDiff1900 计算日期距离1900-01-01的天数
  1007. func GetDaysDiff1900(date string) int {
  1008. // 将字符串转换为时间类型
  1009. //从1899年12月30日开始是因为Excel的日期计算是基于1900年1月1日的,而1900年并不是闰年,因此Excel日期计算存在一个错误。为了修正这个错误,
  1010. //我们将时间回溯到1899年12月30日,这样在进行日期计算时可以正确地处理Excel日期。
  1011. tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
  1012. if err != nil {
  1013. return 0
  1014. }
  1015. tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
  1016. if err != nil {
  1017. return 0
  1018. }
  1019. // 计算两个日期之间的天数差值
  1020. duration := tEnd.Sub(tStart).Hours() / 24
  1021. days := int(duration)
  1022. return days
  1023. }
  1024. func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
  1025. funMap := getFormulaMap()
  1026. for k, v := range funMap {
  1027. formulaStr = strings.Replace(formulaStr, k, v, -1)
  1028. }
  1029. replaceCount := 0
  1030. for tag, val := range valTagMap {
  1031. dvStr := fmt.Sprintf("%v", val)
  1032. formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
  1033. replaceCount++
  1034. }
  1035. for k, v := range funMap {
  1036. formulaStr = strings.Replace(formulaStr, v, k, -1)
  1037. }
  1038. return formulaStr
  1039. }
  1040. // GetFrequencyEn 获取频度的英文版
  1041. func GetFrequencyEn(frequency string) (frequencyEn string) {
  1042. switch frequency {
  1043. case "日度":
  1044. frequencyEn = "day"
  1045. return
  1046. case "周度":
  1047. frequencyEn = "week"
  1048. return
  1049. case "旬度":
  1050. frequencyEn = "ten days"
  1051. return
  1052. case "月度":
  1053. frequencyEn = "month"
  1054. return
  1055. case "季度":
  1056. frequencyEn = "quarter"
  1057. return
  1058. case "年度":
  1059. frequencyEn = "year"
  1060. return
  1061. }
  1062. return
  1063. }
  1064. // DateConvMysqlConvMongo
  1065. // @Description: 将mysql中的日期比较符转换成mongo中的日期比较符
  1066. // @author: Roc
  1067. // @datetime 2024-05-08 11:03:26
  1068. // @param dateCon string
  1069. func DateConvMysqlConvMongo(dateCon string) string {
  1070. cond := ""
  1071. switch dateCon {
  1072. case "=":
  1073. cond = "$eq"
  1074. case "<":
  1075. cond = "$lt"
  1076. case "<=":
  1077. cond = "$lte"
  1078. case ">":
  1079. cond = "$gt"
  1080. case ">=":
  1081. cond = "$gte"
  1082. }
  1083. return cond
  1084. }
  1085. func DesBase64Decrypt(crypted []byte, desKey string) []byte {
  1086. result, _ := base64.StdEncoding.DecodeString(string(crypted))
  1087. remain := len(result) % 8
  1088. if remain > 0 {
  1089. mod := 8 - remain
  1090. for i := 0; i < mod; i++ {
  1091. result = append(result, 0)
  1092. }
  1093. }
  1094. origData, err := TripleDesDecrypt(result, []byte(desKey))
  1095. if err != nil {
  1096. panic(any(err))
  1097. }
  1098. return origData
  1099. }
  1100. // // 3DES解密
  1101. func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
  1102. block, err := des.NewTripleDESCipher(key)
  1103. if err != nil {
  1104. return nil, err
  1105. }
  1106. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  1107. origData := make([]byte, len(crypted))
  1108. // origData := crypted
  1109. blockMode.CryptBlocks(origData, crypted)
  1110. origData = PKCS5UnPadding(origData)
  1111. // origData = ZeroUnPadding(origData)
  1112. return origData, nil
  1113. }
  1114. func PKCS5UnPadding(origData []byte) []byte {
  1115. length := len(origData)
  1116. // 去掉最后一个字节 unpadding 次
  1117. unpadding := int(origData[length-1])
  1118. return origData[:(length - unpadding)]
  1119. }
  1120. func TimeTransferString(format string, t time.Time) string {
  1121. str := t.Format(format)
  1122. if t.IsZero() {
  1123. return ""
  1124. }
  1125. return str
  1126. }
  1127. // handleSystemAppointDateT
  1128. // @Description: 处理系统日期相关的指定频率(所在周/旬/月/季/半年/年的最后/最早一天)
  1129. // @author: Roc
  1130. // @datetime2023-10-27 09:31:35
  1131. // @param Frequency string
  1132. // @param Day string
  1133. // @return date string
  1134. // @return err error
  1135. // @return errMsg string
  1136. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1137. //currDate := time.Now()
  1138. switch frequency {
  1139. case "本周":
  1140. day := int(currDate.Weekday())
  1141. if day == 0 { // 周日
  1142. day = 7
  1143. }
  1144. num := 0
  1145. switch appointDay {
  1146. case "周一":
  1147. num = 1
  1148. case "周二":
  1149. num = 2
  1150. case "周三":
  1151. num = 3
  1152. case "周四":
  1153. num = 4
  1154. case "周五":
  1155. num = 5
  1156. case "周六":
  1157. num = 6
  1158. case "周日":
  1159. num = 7
  1160. }
  1161. day = num - day
  1162. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1163. case "本旬":
  1164. day := currDate.Day()
  1165. var tmpDate time.Time
  1166. switch appointDay {
  1167. case "第一天":
  1168. if day <= 10 {
  1169. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1170. } else if day <= 20 {
  1171. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1172. } else {
  1173. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1174. }
  1175. case "最后一天":
  1176. if day <= 10 {
  1177. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1178. } else if day <= 20 {
  1179. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1180. } else {
  1181. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1182. }
  1183. }
  1184. date = tmpDate.Format(FormatDate)
  1185. case "本月":
  1186. var tmpDate time.Time
  1187. switch appointDay {
  1188. case "第一天":
  1189. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1190. case "最后一天":
  1191. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1192. }
  1193. date = tmpDate.Format(FormatDate)
  1194. case "本季":
  1195. month := currDate.Month()
  1196. var tmpDate time.Time
  1197. switch appointDay {
  1198. case "第一天":
  1199. if month <= 3 {
  1200. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1201. } else if month <= 6 {
  1202. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1203. } else if month <= 9 {
  1204. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1205. } else {
  1206. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1207. }
  1208. case "最后一天":
  1209. if month <= 3 {
  1210. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1211. } else if month <= 6 {
  1212. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1213. } else if month <= 9 {
  1214. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1215. } else {
  1216. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1217. }
  1218. }
  1219. date = tmpDate.Format(FormatDate)
  1220. case "本半年":
  1221. month := currDate.Month()
  1222. var tmpDate time.Time
  1223. switch appointDay {
  1224. case "第一天":
  1225. if month <= 6 {
  1226. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1227. } else {
  1228. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1229. }
  1230. case "最后一天":
  1231. if month <= 6 {
  1232. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1233. } else {
  1234. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1235. }
  1236. }
  1237. date = tmpDate.Format(FormatDate)
  1238. case "本年":
  1239. var tmpDate time.Time
  1240. switch appointDay {
  1241. case "第一天":
  1242. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1243. case "最后一天":
  1244. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1245. }
  1246. date = tmpDate.Format(FormatDate)
  1247. default:
  1248. errMsg = "错误的日期频度:" + frequency
  1249. err = errors.New(errMsg)
  1250. return
  1251. }
  1252. return
  1253. }
  1254. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1255. switch op {
  1256. case "=":
  1257. return a == b
  1258. case ">":
  1259. return a > b
  1260. case ">=":
  1261. return a >= b
  1262. case "<=":
  1263. return a <= b
  1264. case "<":
  1265. return a < b
  1266. }
  1267. return false
  1268. }
  1269. // RoundNumber 保留小数位数
  1270. func RoundNumber(num string, decimalPlaces int, hasPercent bool) string {
  1271. numDecimal, _ := decimal.NewFromString(num)
  1272. if hasPercent {
  1273. numDecimal = numDecimal.Mul(decimal.NewFromInt(100))
  1274. }
  1275. numStr := numDecimal.Round(int32(decimalPlaces)).StringFixed(int32(decimalPlaces))
  1276. if hasPercent {
  1277. numStr += "%"
  1278. }
  1279. return numStr
  1280. }
  1281. // ForwardPars
  1282. // @Description: 向前插入参数
  1283. // @param pars
  1284. // @param values
  1285. // @return []interface{}
  1286. func ForwardPars(pars []interface{}, values ...interface{}) []interface{} {
  1287. if len(values) <= 0 {
  1288. return pars
  1289. }
  1290. return append(values, pars...)
  1291. }
  1292. // GormDateStrToDateTimeStr
  1293. // @Description: gorm日期字符串格式转正常显示的日期时间字符串
  1294. // @param originalString
  1295. // @return formatStr
  1296. func GormDateStrToDateTimeStr(originalString string) (formatStr string) {
  1297. if originalString == `` {
  1298. return
  1299. }
  1300. if strings.Contains(originalString, "0001-01-01") {
  1301. return
  1302. }
  1303. formatStr = originalString
  1304. if !strings.Contains(originalString, "T") {
  1305. return
  1306. }
  1307. // 解析原始字符串
  1308. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1309. if err != nil {
  1310. fmt.Println("Error parsing time:", err)
  1311. return
  1312. }
  1313. // 重新格式化时间
  1314. formatStr = t.Format(FormatDateTime)
  1315. return
  1316. }
  1317. // GormDateStrToDateStr
  1318. // @Description: gorm日期字符串格式转正常显示的日期字符串
  1319. // @param originalString
  1320. // @return formatStr
  1321. func GormDateStrToDateStr(originalString string) (formatStr string) {
  1322. if originalString == `` {
  1323. return
  1324. }
  1325. if strings.Contains(originalString, "0001-01-01") {
  1326. return
  1327. }
  1328. formatStr = originalString
  1329. if !strings.Contains(originalString, "T") {
  1330. return
  1331. }
  1332. // 解析原始字符串
  1333. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1334. if err != nil {
  1335. fmt.Println("Error parsing time:", err)
  1336. return
  1337. }
  1338. // 重新格式化时间
  1339. formatStr = t.Format(FormatDate)
  1340. return
  1341. }