common.go 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. package utils
  2. import (
  3. "bufio"
  4. "crypto/md5"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "github.com/shopspring/decimal"
  12. "image"
  13. "image/png"
  14. "io"
  15. "math"
  16. "math/rand"
  17. "net"
  18. "net/http"
  19. "os"
  20. "os/exec"
  21. "path"
  22. "regexp"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "unicode"
  28. )
  29. func GetRandString(size int) string {
  30. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  31. randomSb := ""
  32. digitSize := len(allLetterDigit)
  33. // 随机数种子
  34. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  35. for i := 0; i < size; i++ {
  36. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  37. }
  38. return randomSb
  39. }
  40. func GetRandStringNoSpecialChar(size int) string {
  41. 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"}
  42. randomSb := ""
  43. digitSize := len(allLetterDigit)
  44. // 随机数种子
  45. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  46. for i := 0; i < size; i++ {
  47. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  48. }
  49. return randomSb
  50. }
  51. func StringsToJSON(str string) string {
  52. rs := []rune(str)
  53. jsons := ""
  54. for _, r := range rs {
  55. rint := int(r)
  56. if rint < 128 {
  57. jsons += string(r)
  58. } else {
  59. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  60. }
  61. }
  62. return jsons
  63. }
  64. func ToString(v interface{}) string {
  65. data, _ := json.Marshal(v)
  66. return string(data)
  67. }
  68. func MD5(data string) string {
  69. m := md5.Sum([]byte(data))
  70. return hex.EncodeToString(m[:])
  71. }
  72. func GetRandDigit(n int) string {
  73. // 随机数种子
  74. rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
  75. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  76. }
  77. func GetToday(format string) string {
  78. today := time.Now().Format(format)
  79. return today
  80. }
  81. func GetTodayLastSecond() time.Duration {
  82. today := GetToday(FormatDate) + " 23:59:59"
  83. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  84. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  85. }
  86. func GetBrithDate(idcard string) string {
  87. l := len(idcard)
  88. var s string
  89. if l == 15 {
  90. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  91. return s
  92. }
  93. if l == 18 {
  94. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  95. return s
  96. }
  97. return GetToday(FormatDate)
  98. }
  99. func WhichSexByIdcard(idcard string) string {
  100. var sexs = [2]string{"女", "男"}
  101. length := len(idcard)
  102. if length == 18 {
  103. sex, _ := strconv.Atoi(string(idcard[16]))
  104. return sexs[sex%2]
  105. } else if length == 15 {
  106. sex, _ := strconv.Atoi(string(idcard[14]))
  107. return sexs[sex%2]
  108. }
  109. return "男"
  110. }
  111. func SubFloatToString(f float64, m int) string {
  112. n := strconv.FormatFloat(f, 'f', -1, 64)
  113. if n == "" {
  114. return ""
  115. }
  116. if m >= len(n) {
  117. return n
  118. }
  119. newn := strings.Split(n, ".")
  120. if m == 0 {
  121. return newn[0]
  122. }
  123. if len(newn) < 2 || m >= len(newn[1]) {
  124. return n
  125. }
  126. return newn[0] + "." + newn[1][:m]
  127. }
  128. func SubFloatToFloat(f float64, m int) float64 {
  129. newn := SubFloatToString(f, m)
  130. newf, _ := strconv.ParseFloat(newn, 64)
  131. return newf
  132. }
  133. func SubFloatToFloatStr(f float64, m int) string {
  134. newn := SubFloatToString(f, m)
  135. return newn
  136. }
  137. func GetYearDiffer(start_time, end_time string) int {
  138. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  139. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  140. age := t2.Year() - t1.Year()
  141. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  142. age--
  143. }
  144. return age
  145. }
  146. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  147. diff := end_time.Unix() - start_time.Unix()
  148. return diff
  149. }
  150. func FixFloat(f float64, m int) float64 {
  151. newn := SubFloatToString(f+0.00000001, m)
  152. newf, _ := strconv.ParseFloat(newn, 64)
  153. return newf
  154. }
  155. func StrListToString(strList []string) (str string) {
  156. if len(strList) > 0 {
  157. for k, v := range strList {
  158. if k == 0 {
  159. str = v
  160. } else {
  161. str = str + "," + v
  162. }
  163. }
  164. return
  165. }
  166. return ""
  167. }
  168. func GetToken() string {
  169. randStr := GetRandString(64)
  170. token := MD5(randStr + Md5Key)
  171. tokenLen := 64 - len(token)
  172. return strings.ToUpper(token + GetRandString(tokenLen))
  173. }
  174. func ErrNoRow() string {
  175. return "record not found"
  176. }
  177. func FileIsExist(filePath string) bool {
  178. _, err := os.Stat(filePath)
  179. return err == nil || os.IsExist(err)
  180. }
  181. func GetImgExt(file string) (ext string, err error) {
  182. var headerByte []byte
  183. headerByte = make([]byte, 8)
  184. fd, err := os.Open(file)
  185. if err != nil {
  186. return "", err
  187. }
  188. defer fd.Close()
  189. _, err = fd.Read(headerByte)
  190. if err != nil {
  191. return "", err
  192. }
  193. xStr := fmt.Sprintf("%x", headerByte)
  194. switch {
  195. case xStr == "89504e470d0a1a0a":
  196. ext = ".png"
  197. case xStr == "0000010001002020":
  198. ext = ".ico"
  199. case xStr == "0000020001002020":
  200. ext = ".cur"
  201. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  202. ext = ".gif"
  203. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  204. ext = ".tga"
  205. case xStr[:8] == "464f524d":
  206. ext = ".iff"
  207. case xStr[:8] == "52494646":
  208. ext = ".ani"
  209. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  210. ext = ".tiff"
  211. case xStr[:4] == "424d":
  212. ext = ".bmp"
  213. case xStr[:4] == "ffd8":
  214. ext = ".jpg"
  215. case xStr[:2] == "0a":
  216. ext = ".pcx"
  217. default:
  218. ext = ""
  219. }
  220. return ext, nil
  221. }
  222. func SaveImage(path string, img image.Image) (err error) {
  223. imgfile, err := os.Create(path)
  224. defer imgfile.Close()
  225. err = png.Encode(imgfile, img)
  226. return err
  227. }
  228. func DownloadImage(imgUrl string) (filePath string, err error) {
  229. imgPath := "./static/imgs/"
  230. fileName := path.Base(imgUrl)
  231. res, err := http.Get(imgUrl)
  232. if err != nil {
  233. fmt.Println("A error occurred!")
  234. return
  235. }
  236. defer res.Body.Close()
  237. reader := bufio.NewReaderSize(res.Body, 32*1024)
  238. filePath = imgPath + fileName
  239. file, err := os.Create(filePath)
  240. if err != nil {
  241. return
  242. }
  243. writer := bufio.NewWriter(file)
  244. written, _ := io.Copy(writer, reader)
  245. fmt.Printf("Total length: %d \n", written)
  246. return
  247. }
  248. func SaveBase64ToFile(content, path string) error {
  249. data, err := base64.StdEncoding.DecodeString(content)
  250. if err != nil {
  251. return err
  252. }
  253. f, err := os.Create(path)
  254. defer f.Close()
  255. if err != nil {
  256. return err
  257. }
  258. f.Write(data)
  259. return nil
  260. }
  261. func SaveBase64ToFileBySeek(content, path string) (err error) {
  262. data, err := base64.StdEncoding.DecodeString(content)
  263. exist, err := PathExists(path)
  264. if err != nil {
  265. return
  266. }
  267. if !exist {
  268. f, err := os.Create(path)
  269. if err != nil {
  270. return err
  271. }
  272. n, _ := f.Seek(0, 2)
  273. _, err = f.WriteAt([]byte(data), n)
  274. defer f.Close()
  275. } else {
  276. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  277. if err != nil {
  278. return err
  279. }
  280. n, _ := f.Seek(0, 2)
  281. _, err = f.WriteAt([]byte(data), n)
  282. defer f.Close()
  283. }
  284. return nil
  285. }
  286. func PathExists(path string) (bool, error) {
  287. _, err := os.Stat(path)
  288. if err == nil {
  289. return true, nil
  290. }
  291. if os.IsNotExist(err) {
  292. return false, nil
  293. }
  294. return false, err
  295. }
  296. func StartIndex(page, pagesize int) int {
  297. if page > 1 {
  298. return (page - 1) * pagesize
  299. }
  300. return 0
  301. }
  302. func PageCount(count, pagesize int) int {
  303. if count%pagesize > 0 {
  304. return count/pagesize + 1
  305. } else {
  306. return count / pagesize
  307. }
  308. }
  309. func TrimHtml(src string) string {
  310. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  311. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  312. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  313. src = re.ReplaceAllString(src, "[图片]")
  314. re, _ = regexp.Compile("class[\\S\\s]+?>")
  315. src = re.ReplaceAllString(src, "")
  316. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  317. src = re.ReplaceAllString(src, "")
  318. return strings.TrimSpace(src)
  319. }
  320. func TimeToTimestamp() {
  321. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  322. }
  323. func ToUnicode(text string) string {
  324. textQuoted := strconv.QuoteToASCII(text)
  325. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  326. return textUnquoted
  327. }
  328. func VersionToInt(version string) int {
  329. version = strings.Replace(version, ".", "", -1)
  330. n, _ := strconv.Atoi(version)
  331. return n
  332. }
  333. func IsCheckInList(list []int, s int) bool {
  334. for _, v := range list {
  335. if v == s {
  336. return true
  337. }
  338. }
  339. return false
  340. }
  341. func round(num float64) int {
  342. return int(num + math.Copysign(0.5, num))
  343. }
  344. func toFixed(num float64, precision int) float64 {
  345. output := math.Pow(10, float64(precision))
  346. return float64(round(num*output)) / output
  347. }
  348. func GetWilsonScore(p, n float64) float64 {
  349. if p == 0 && n == 0 {
  350. return 0
  351. }
  352. 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)
  353. }
  354. func ChangeWordsToNum(str string) (numStr string) {
  355. words := ([]rune)(str)
  356. num := 0
  357. n := 0
  358. for i := 0; i < len(words); i++ {
  359. word := string(words[i : i+1])
  360. switch word {
  361. case "万":
  362. if n == 0 {
  363. n = 1
  364. }
  365. n = n * 10000
  366. num = num*10000 + n
  367. n = 0
  368. case "千":
  369. if n == 0 {
  370. n = 1
  371. }
  372. n = n * 1000
  373. num += n
  374. n = 0
  375. case "百":
  376. if n == 0 {
  377. n = 1
  378. }
  379. n = n * 100
  380. num += n
  381. n = 0
  382. case "十":
  383. if n == 0 {
  384. n = 1
  385. }
  386. n = n * 10
  387. num += n
  388. n = 0
  389. case "一":
  390. n += 1
  391. case "二":
  392. n += 2
  393. case "三":
  394. n += 3
  395. case "四":
  396. n += 4
  397. case "五":
  398. n += 5
  399. case "六":
  400. n += 6
  401. case "七":
  402. n += 7
  403. case "八":
  404. n += 8
  405. case "九":
  406. n += 9
  407. case "零":
  408. default:
  409. if n > 0 {
  410. num += n
  411. n = 0
  412. }
  413. if num == 0 {
  414. numStr += word
  415. } else {
  416. numStr += strconv.Itoa(num) + word
  417. num = 0
  418. }
  419. }
  420. }
  421. if n > 0 {
  422. num += n
  423. n = 0
  424. }
  425. if num != 0 {
  426. numStr += strconv.Itoa(num)
  427. }
  428. return
  429. }
  430. func Sha1(data string) string {
  431. sha1 := sha1.New()
  432. sha1.Write([]byte(data))
  433. return hex.EncodeToString(sha1.Sum([]byte("")))
  434. }
  435. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  436. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  437. out, err := exec.Command("bash", "-c", cmd).Output()
  438. if err != nil {
  439. return
  440. }
  441. outTimes := string(out)
  442. fmt.Println("outTimes:", outTimes)
  443. if outTimes != "" {
  444. timeArr := strings.Split(outTimes, ":")
  445. h := timeArr[0]
  446. m := timeArr[1]
  447. s := timeArr[2]
  448. hInt, err := strconv.Atoi(h)
  449. if err != nil {
  450. return playSeconds, err
  451. }
  452. mInt, err := strconv.Atoi(m)
  453. if err != nil {
  454. return playSeconds, err
  455. }
  456. s = strings.Trim(s, " ")
  457. s = strings.Trim(s, "\n")
  458. sInt, err := strconv.ParseFloat(s, 64)
  459. if err != nil {
  460. return playSeconds, err
  461. }
  462. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  463. }
  464. return
  465. }
  466. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  467. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  468. tradeCode = strings.Trim(tradeCode, " ")
  469. tradeCodeInt, err := strconv.Atoi(tradeCode)
  470. if err != nil {
  471. return
  472. }
  473. tradeCodeInt = tradeCodeInt + 1
  474. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  475. return
  476. }
  477. func ConvertToFormatDay(excelDaysString string) string {
  478. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  479. curDiffDay := excelDaysString
  480. b, _ := strconv.Atoi(curDiffDay)
  481. realDiffDay := b - baseDiffDay
  482. realDiffSecond := realDiffDay * 24 * 3600
  483. baseOriginSecond := 1136185445
  484. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  485. return resultTime
  486. }
  487. func CheckPwd(pwd string) bool {
  488. compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
  489. reg := regexp.MustCompile(compile)
  490. flag := reg.MatchString(pwd)
  491. return flag
  492. }
  493. func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
  494. if len(myMonth) == 1 {
  495. myMonth = "0" + myMonth
  496. }
  497. yInt, _ := strconv.Atoi(myYear)
  498. timeLayout := "2006-01-02 15:04:05"
  499. loc, _ := time.LoadLocation("Local")
  500. theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
  501. newMonth := theTime.Month()
  502. t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  503. t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
  504. return t1, t2
  505. }
  506. func TrimStr(str string) (str2 string) {
  507. if str == "" {
  508. return str
  509. }
  510. return strings.Replace(str, " ", "", -1)
  511. }
  512. func StrTimeToTime(strTime string) time.Time {
  513. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  514. loc, _ := time.LoadLocation("Local") //重要:获取时区
  515. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  516. return resultTime
  517. }
  518. func StrDateTimeToWeek(strTime string) string {
  519. var WeekDayMap = map[string]string{
  520. "Monday": "周一",
  521. "Tuesday": "周二",
  522. "Wednesday": "周三",
  523. "Thursday": "周四",
  524. "Friday": "周五",
  525. "Saturday": "周六",
  526. "Sunday": "周日",
  527. }
  528. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  529. startday, _ := time.ParseInLocation("2006-01-02", ctime, time.Local)
  530. staweek_int := startday.Weekday().String()
  531. return WeekDayMap[staweek_int]
  532. }
  533. func TimeToStrYmd(time2 time.Time) string {
  534. var Ymd string
  535. year := time2.Year()
  536. month := time2.Format("1")
  537. day1 := time.Now().Day()
  538. Ymd = strconv.Itoa(year) + "年" + month + "月" + strconv.Itoa(day1) + "日"
  539. return Ymd
  540. }
  541. func TimeRemoveHms(strTime string) string {
  542. var Ymd string
  543. var resultTime = StrTimeToTime(strTime)
  544. year := resultTime.Year()
  545. month := resultTime.Format("01")
  546. day1 := resultTime.Day()
  547. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  548. return Ymd
  549. }
  550. func TimeRemoveHms2(strTime string) string {
  551. var Ymd string
  552. var resultTime = StrTimeToTime(strTime)
  553. year := resultTime.Year()
  554. month := resultTime.Format("01")
  555. day1 := resultTime.Day()
  556. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  557. return Ymd
  558. }
  559. func ArticleLastTime(strTime string) string {
  560. var newTime string
  561. stamp, _ := time.ParseInLocation("2006-01-02 15:04:05", strTime, time.Local)
  562. diffTime := time.Now().Unix() - stamp.Unix()
  563. if diffTime <= 60 {
  564. newTime = "当前"
  565. } else if diffTime < 60*60 {
  566. newTime = strconv.FormatInt(diffTime/60, 10) + "分钟前"
  567. } else if diffTime < 24*60*60 {
  568. newTime = strconv.FormatInt(diffTime/(60*60), 10) + "小时前"
  569. } else if diffTime < 30*24*60*60 {
  570. newTime = strconv.FormatInt(diffTime/(24*60*60), 10) + "天前"
  571. } else if diffTime < 12*30*24*60*60 {
  572. newTime = strconv.FormatInt(diffTime/(30*24*60*60), 10) + "月前"
  573. } else {
  574. newTime = "1年前"
  575. }
  576. return newTime
  577. }
  578. func ConvertNumToCny(num float64) (str string, err error) {
  579. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  580. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  581. s := sliceUnit[len(sliceUnit)-len(strNum):]
  582. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  583. for k, v := range strNum[:] {
  584. str = str + upperDigitUnit[string(v)] + s[k]
  585. }
  586. reg, err := regexp.Compile(`零角零分$`)
  587. str = reg.ReplaceAllString(str, "整")
  588. reg, err = regexp.Compile(`零角`)
  589. str = reg.ReplaceAllString(str, "零")
  590. reg, err = regexp.Compile(`零分$`)
  591. str = reg.ReplaceAllString(str, "整")
  592. reg, err = regexp.Compile(`零[仟佰拾]`)
  593. str = reg.ReplaceAllString(str, "零")
  594. reg, err = regexp.Compile(`零{2,}`)
  595. str = reg.ReplaceAllString(str, "零")
  596. reg, err = regexp.Compile(`零亿`)
  597. str = reg.ReplaceAllString(str, "亿")
  598. reg, err = regexp.Compile(`零万`)
  599. str = reg.ReplaceAllString(str, "万")
  600. reg, err = regexp.Compile(`零*元`)
  601. str = reg.ReplaceAllString(str, "元")
  602. reg, err = regexp.Compile(`亿零{0, 3}万`)
  603. str = reg.ReplaceAllString(str, "^元")
  604. reg, err = regexp.Compile(`零元`)
  605. str = reg.ReplaceAllString(str, "零")
  606. return
  607. }
  608. func GetNowWeekMonday() time.Time {
  609. offset := int(time.Monday - time.Now().Weekday())
  610. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  611. offset = -6
  612. }
  613. mondayTime := time.Now().AddDate(0, 0, offset)
  614. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  615. return mondayTime
  616. }
  617. func GetNowWeekLastDay() time.Time {
  618. offset := int(time.Monday - time.Now().Weekday())
  619. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  620. offset = -6
  621. }
  622. firstDayTime := time.Now().AddDate(0, 0, offset)
  623. firstDayTime = time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 0, 0, 0, 0, firstDayTime.Location()).AddDate(0, 0, 6)
  624. lastDayTime := time.Date(firstDayTime.Year(), firstDayTime.Month(), firstDayTime.Day(), 23, 59, 59, 0, firstDayTime.Location())
  625. return lastDayTime
  626. }
  627. func GetNowMonthFirstDay() time.Time {
  628. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  629. return nowMonthFirstDay
  630. }
  631. func GetNowMonthLastDay() time.Time {
  632. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  633. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  634. return nowMonthLastDay
  635. }
  636. func GetNowQuarterFirstDay() time.Time {
  637. month := int(time.Now().Month())
  638. var nowQuarterFirstDay time.Time
  639. if month >= 1 && month <= 3 {
  640. nowQuarterFirstDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  641. } else if month >= 4 && month <= 6 {
  642. nowQuarterFirstDay = time.Date(time.Now().Year(), 4, 1, 0, 0, 0, 0, time.Now().Location())
  643. } else if month >= 7 && month <= 9 {
  644. nowQuarterFirstDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  645. } else {
  646. nowQuarterFirstDay = time.Date(time.Now().Year(), 10, 1, 0, 0, 0, 0, time.Now().Location())
  647. }
  648. return nowQuarterFirstDay
  649. }
  650. func GetNowQuarterLastDay() time.Time {
  651. month := int(time.Now().Month())
  652. var nowQuarterLastDay time.Time
  653. if month >= 1 && month <= 3 {
  654. nowQuarterLastDay = time.Date(time.Now().Year(), 3, 31, 23, 59, 59, 0, time.Now().Location())
  655. } else if month >= 4 && month <= 6 {
  656. nowQuarterLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  657. } else if month >= 7 && month <= 9 {
  658. nowQuarterLastDay = time.Date(time.Now().Year(), 9, 30, 23, 59, 59, 0, time.Now().Location())
  659. } else {
  660. nowQuarterLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  661. }
  662. return nowQuarterLastDay
  663. }
  664. func GetNowHalfYearFirstDay() time.Time {
  665. month := int(time.Now().Month())
  666. var nowHalfYearLastDay time.Time
  667. if month >= 1 && month <= 6 {
  668. nowHalfYearLastDay = time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  669. } else {
  670. nowHalfYearLastDay = time.Date(time.Now().Year(), 7, 1, 0, 0, 0, 0, time.Now().Location())
  671. }
  672. return nowHalfYearLastDay
  673. }
  674. func GetNowHalfYearLastDay() time.Time {
  675. month := int(time.Now().Month())
  676. var nowHalfYearLastDay time.Time
  677. if month >= 1 && month <= 6 {
  678. nowHalfYearLastDay = time.Date(time.Now().Year(), 6, 30, 23, 59, 59, 0, time.Now().Location())
  679. } else {
  680. nowHalfYearLastDay = time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  681. }
  682. return nowHalfYearLastDay
  683. }
  684. func GetNowYearFirstDay() time.Time {
  685. nowYearFirstDay := time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.Now().Location())
  686. return nowYearFirstDay
  687. }
  688. func GetNowYearLastDay() time.Time {
  689. nowYearLastDay := time.Date(time.Now().Year(), 12, 31, 23, 59, 59, 0, time.Now().Location())
  690. return nowYearLastDay
  691. }
  692. func FormatPrice(price float64) (str string) {
  693. str = decimal.NewFromFloat(price).String()
  694. length := len(str)
  695. if length < 4 {
  696. return str
  697. }
  698. arr := strings.Split(str, ".") //用小数点符号分割字符串,为数组接收
  699. length1 := len(arr[0])
  700. if length1 < 4 {
  701. return str
  702. }
  703. count := (length1 - 1) / 3
  704. for i := 0; i < count; i++ {
  705. arr[0] = arr[0][:length1-(i+1)*3] + "," + arr[0][length1-(i+1)*3:]
  706. }
  707. return strings.Join(arr, ".") //将一系列字符串连接为一个字符串,之间用sep来分隔。
  708. }
  709. func getMonthDay(year, month int) (days int) {
  710. if month != 2 {
  711. if month == 4 || month == 6 || month == 9 || month == 11 {
  712. days = 30
  713. } else {
  714. days = 31
  715. }
  716. } else {
  717. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  718. days = 29
  719. } else {
  720. days = 28
  721. }
  722. }
  723. return
  724. }
  725. func SaveToFile(content, path string) error {
  726. f, err := os.Create(path)
  727. defer f.Close()
  728. if err != nil {
  729. return err
  730. }
  731. f.Write([]byte(content))
  732. return nil
  733. }
  734. func HideString(src string, hideLen int) string {
  735. if src == "" {
  736. return src
  737. }
  738. str := []rune(src)
  739. if hideLen == 0 {
  740. hideLen = 4
  741. }
  742. hideStr := ""
  743. for i := 0; i < hideLen; i++ {
  744. hideStr += "*"
  745. }
  746. strLen := len(str)
  747. if strLen == 1 {
  748. return string(str[:1]) + hideStr
  749. }
  750. if strLen <= hideLen+2 {
  751. return string(str[:1]) + hideStr + string(str[strLen-1:])
  752. }
  753. subLen := strLen - hideLen //剩余需要展示的字符长度
  754. decimal.NewFromFloat(2)
  755. frontLenDecimal := decimal.NewFromInt(int64(subLen)).Div(decimal.NewFromInt(2)) //前面需要展示的字符的长度
  756. frontLen := frontLenDecimal.Floor().IntPart()
  757. return string(str[:frontLen]) + hideStr + string(str[frontLen+int64(hideLen):])
  758. }
  759. func GetAttendanceDetailSeconds(secondNum int) string {
  760. var timeStr string
  761. if secondNum <= 60 {
  762. if secondNum < 10 {
  763. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  764. } else {
  765. timeStr = strconv.Itoa(secondNum) + "''"
  766. }
  767. } else {
  768. var remainderStr string
  769. remainderNum := secondNum % 60
  770. minuteNum := secondNum / 60
  771. if remainderNum < 10 {
  772. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  773. } else {
  774. remainderStr = strconv.Itoa(remainderNum) + "''"
  775. }
  776. if minuteNum < 10 {
  777. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  778. } else {
  779. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  780. }
  781. }
  782. return timeStr
  783. }
  784. func SubStr(str string, subLen int) string {
  785. strRune := []rune(str)
  786. bodyRuneLen := len(strRune)
  787. if bodyRuneLen > subLen {
  788. bodyRuneLen = subLen
  789. }
  790. str = string(strRune[:bodyRuneLen])
  791. return str
  792. }
  793. func GetLocalIP() (ip string, err error) {
  794. addrs, err := net.InterfaceAddrs()
  795. if err != nil {
  796. return
  797. }
  798. for _, addr := range addrs {
  799. ipAddr, ok := addr.(*net.IPNet)
  800. if !ok {
  801. continue
  802. }
  803. if ipAddr.IP.IsLoopback() {
  804. continue
  805. }
  806. if !ipAddr.IP.IsGlobalUnicast() {
  807. continue
  808. }
  809. return ipAddr.IP.String(), nil
  810. }
  811. return
  812. }
  813. func PrintLog(params ...string) {
  814. _, file, line, ok := runtime.Caller(1)
  815. fmt.Println(file, line, ok, params)
  816. }
  817. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  818. for _, id := range idStrList {
  819. if id == searchId {
  820. has = true
  821. return
  822. }
  823. }
  824. return
  825. }
  826. func InArrayByInt(idStrList []int, searchId int) (has bool) {
  827. for _, id := range idStrList {
  828. if id == searchId {
  829. has = true
  830. return
  831. }
  832. }
  833. return
  834. }
  835. func GetOrmInReplace(num int) string {
  836. return "?"
  837. }
  838. func GetTimeSubDay(t1, t2 time.Time) int {
  839. var day int
  840. swap := false
  841. if t1.Unix() > t2.Unix() {
  842. t1, t2 = t2, t1
  843. swap = true
  844. }
  845. t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
  846. day = int(t2.Sub(t1).Hours() / 24)
  847. if t1_.Day() != t1.Day() {
  848. day += 1
  849. }
  850. if swap {
  851. day = -day
  852. }
  853. return day
  854. }
  855. func GetFrequencyEndDay(currDate time.Time, frequency string) (endDate time.Time) {
  856. switch frequency {
  857. case "周度":
  858. if currDate.Weekday() == 0 {
  859. endDate = currDate
  860. } else {
  861. endDate = currDate.AddDate(0, 0, 7-int(currDate.Weekday()))
  862. }
  863. case "旬度":
  864. nextDay := currDate.AddDate(0, 0, 1)
  865. if nextDay.Day() == 1 || currDate.Day() == 10 || currDate.Day() == 20 {
  866. endDate = currDate
  867. } else {
  868. if currDate.Day() < 10 { // 每月10号
  869. endDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, time.Local)
  870. } else if currDate.Day() < 20 { // 每月10号
  871. endDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, time.Local)
  872. } else {
  873. tmpNextMonth := currDate.AddDate(0, 0, 13)
  874. endDate = time.Date(tmpNextMonth.Year(), tmpNextMonth.Month(), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  875. }
  876. }
  877. case "月度":
  878. nextDay := currDate.AddDate(0, 0, 1)
  879. if nextDay.Day() == 1 {
  880. endDate = currDate
  881. } else {
  882. endDate = time.Date(nextDay.Year(), nextDay.Month()+1, 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1)
  883. }
  884. case "季度":
  885. nextDay := currDate.AddDate(0, 0, 1)
  886. if (nextDay.Month() == 1 || nextDay.Month() == 4 || nextDay.Month() == 7 || nextDay.Month() == 10) && nextDay.Day() == 1 {
  887. endDate = currDate
  888. } else {
  889. if currDate.Month() < 4 { // 1季度
  890. endDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, time.Local)
  891. } else if currDate.Month() < 7 { // 2季度
  892. endDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, time.Local)
  893. } else if currDate.Month() < 10 { // 3季度
  894. endDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, time.Local)
  895. } else {
  896. endDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  897. }
  898. }
  899. case "年度":
  900. endDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, time.Local)
  901. default:
  902. endDate = currDate
  903. return
  904. }
  905. return
  906. }
  907. func CheckFrequency(leftFrequency, rightFrequency string) int {
  908. frequencyMap := map[string]int{
  909. "年度": 0,
  910. "半年度": 1,
  911. "季度": 2,
  912. "月度": 3,
  913. "旬度": 4,
  914. "周度": 5,
  915. "日度": 6,
  916. }
  917. return frequencyMap[leftFrequency] - frequencyMap[rightFrequency]
  918. }
  919. func SnakeToCamel(s string) string {
  920. var result string
  921. upper := true
  922. for _, c := range s {
  923. if c == '_' {
  924. upper = true
  925. continue
  926. }
  927. if upper {
  928. result += string(unicode.ToUpper(c))
  929. upper = false
  930. } else {
  931. result += string(c)
  932. }
  933. }
  934. return result
  935. }
  936. func CamelToSnake(s string) string {
  937. var result string
  938. for i, c := range s {
  939. if unicode.IsUpper(c) {
  940. if i > 0 {
  941. result += "_"
  942. }
  943. result += string(unicode.ToLower(c))
  944. } else {
  945. result += string(c)
  946. }
  947. }
  948. return result
  949. }
  950. func TimeTransferString(format string, t time.Time) string {
  951. str := t.Format(format)
  952. if t.IsZero() {
  953. return ""
  954. }
  955. return str
  956. }
  957. func GetEdbRefreshStartDate(startDate string) string {
  958. if startDate == `` || strings.Contains(startDate, "0000-") {
  959. return "1990-01-01"
  960. }
  961. return startDate
  962. }
  963. func GetEdbRefreshEndDate(endDate string) string {
  964. if endDate == `` || strings.Contains(endDate, "0000-") {
  965. return time.Now().Format(FormatDate)
  966. }
  967. return endDate
  968. }
  969. func FloatAlmostEqual(a, b float64) bool {
  970. epsilon := 1e-9 // 容差值
  971. return math.Abs(a-b) <= epsilon
  972. }
  973. func VerifyFrequency(frequency string) bool {
  974. return InArrayByStr([]string{"年度", "半年度", "季度", "月度", "旬度", "周度", "日度"}, frequency)
  975. }
  976. func DateConvMysqlConvMongo(dateCon string) string {
  977. cond := ""
  978. switch dateCon {
  979. case "=":
  980. cond = "$eq"
  981. case "<":
  982. cond = "$lt"
  983. case "<=":
  984. cond = "$lte"
  985. case ">":
  986. cond = "$gt"
  987. case ">=":
  988. cond = "$gte"
  989. }
  990. return cond
  991. }
  992. var GenerateEdbCodeMap = map[string]bool{}
  993. func GenerateEdbCode(num int, pre string) (edbCode string, err error) {
  994. if num >= 10 {
  995. err = errors.New("指标编码生成失败,请重新生成")
  996. return
  997. }
  998. randStr := GetRandDigit(4)
  999. edbCode = `C` + pre + time.Now().Format(FormatShortDateTimeUnSpace) + randStr
  1000. if _, ok := GenerateEdbCodeMap[edbCode]; ok {
  1001. num++
  1002. edbCode, err = GenerateEdbCode(num, pre)
  1003. }
  1004. GenerateEdbCodeMap[edbCode] = true
  1005. return
  1006. }
  1007. func InsertStr2StrIdx(str, sep string, idx int, value string) string {
  1008. str = strings.TrimSpace(str)
  1009. if sep == "" {
  1010. sep = " "
  1011. }
  1012. slice := strings.Split(str, sep)
  1013. if len(slice) < 2 {
  1014. return str
  1015. }
  1016. if idx < 0 || idx > len(slice) {
  1017. return str
  1018. }
  1019. slice = append(slice[:idx], append([]string{value}, slice[idx:]...)...)
  1020. return strings.Join(slice, sep)
  1021. }
  1022. func FormatFloatPlaces(val float64, places int32) (newVal float64, err error) {
  1023. if places <= 0 {
  1024. places = 4
  1025. }
  1026. strNewVal := decimal.NewFromFloat(val).Round(places).String()
  1027. di, e := decimal.NewFromString(strNewVal)
  1028. if e != nil {
  1029. err = fmt.Errorf("NewFromString err: %v", e)
  1030. return
  1031. }
  1032. newVal, _ = di.Float64()
  1033. return
  1034. }
  1035. func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
  1036. switch frequency {
  1037. case "本周":
  1038. day := int(currDate.Weekday())
  1039. if day == 0 { // 周日
  1040. day = 7
  1041. }
  1042. num := 0
  1043. switch appointDay {
  1044. case "周一":
  1045. num = 1
  1046. case "周二":
  1047. num = 2
  1048. case "周三":
  1049. num = 3
  1050. case "周四":
  1051. num = 4
  1052. case "周五":
  1053. num = 5
  1054. case "周六":
  1055. num = 6
  1056. case "周日":
  1057. num = 7
  1058. }
  1059. day = num - day
  1060. date = currDate.AddDate(0, 0, day).Format(FormatDate)
  1061. case "本旬":
  1062. day := currDate.Day()
  1063. var tmpDate time.Time
  1064. switch appointDay {
  1065. case "第一天":
  1066. if day <= 10 {
  1067. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1068. } else if day <= 20 {
  1069. tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
  1070. } else {
  1071. tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
  1072. }
  1073. case "最后一天":
  1074. if day <= 10 {
  1075. tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
  1076. } else if day <= 20 {
  1077. tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
  1078. } else {
  1079. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1080. }
  1081. }
  1082. date = tmpDate.Format(FormatDate)
  1083. case "本月":
  1084. var tmpDate time.Time
  1085. switch appointDay {
  1086. case "第一天":
  1087. tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
  1088. case "最后一天":
  1089. tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
  1090. }
  1091. date = tmpDate.Format(FormatDate)
  1092. case "本季":
  1093. month := currDate.Month()
  1094. var tmpDate time.Time
  1095. switch appointDay {
  1096. case "第一天":
  1097. if month <= 3 {
  1098. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1099. } else if month <= 6 {
  1100. tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
  1101. } else if month <= 9 {
  1102. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1103. } else {
  1104. tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
  1105. }
  1106. case "最后一天":
  1107. if month <= 3 {
  1108. tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
  1109. } else if month <= 6 {
  1110. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1111. } else if month <= 9 {
  1112. tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
  1113. } else {
  1114. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1115. }
  1116. }
  1117. date = tmpDate.Format(FormatDate)
  1118. case "本半年":
  1119. month := currDate.Month()
  1120. var tmpDate time.Time
  1121. switch appointDay {
  1122. case "第一天":
  1123. if month <= 6 {
  1124. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1125. } else {
  1126. tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
  1127. }
  1128. case "最后一天":
  1129. if month <= 6 {
  1130. tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
  1131. } else {
  1132. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1133. }
  1134. }
  1135. date = tmpDate.Format(FormatDate)
  1136. case "本年":
  1137. var tmpDate time.Time
  1138. switch appointDay {
  1139. case "第一天":
  1140. tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
  1141. case "最后一天":
  1142. tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
  1143. }
  1144. date = tmpDate.Format(FormatDate)
  1145. default:
  1146. errMsg = "错误的日期频度:" + frequency
  1147. err = errors.New(errMsg)
  1148. return
  1149. }
  1150. return
  1151. }
  1152. func CompareFloatByOpStrings(op string, a, b float64) bool {
  1153. switch op {
  1154. case "=":
  1155. return a == b
  1156. case ">":
  1157. return a > b
  1158. case ">=":
  1159. return a >= b
  1160. case "<=":
  1161. return a <= b
  1162. case "<":
  1163. return a < b
  1164. }
  1165. return false
  1166. }
  1167. func IsDivideZero(err error) bool {
  1168. if err == nil {
  1169. return false
  1170. }
  1171. if strings.Contains(err.Error(), "division by zero") {
  1172. return true
  1173. }
  1174. return false
  1175. }
  1176. func GetTradingDays(startDate, endDate time.Time) []time.Time {
  1177. var tradingDays []time.Time
  1178. for curr := startDate; !curr.After(endDate); curr = curr.AddDate(0, 0, 1) {
  1179. if curr.Weekday() >= time.Monday && curr.Weekday() <= time.Friday {
  1180. tradingDays = append(tradingDays, curr)
  1181. }
  1182. }
  1183. return tradingDays
  1184. }
  1185. func GormDateStrToDateTimeStr(originalString string) (formatStr string) {
  1186. formatStr = originalString
  1187. if !strings.Contains(originalString, "T") {
  1188. return
  1189. }
  1190. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1191. if err != nil {
  1192. fmt.Println("Error parsing time:", err)
  1193. return
  1194. }
  1195. formatStr = t.Format(FormatDateTime)
  1196. return
  1197. }
  1198. func GormDateStrToDateStr(originalString string) (formatStr string) {
  1199. formatStr = originalString
  1200. if !strings.Contains(originalString, "T") {
  1201. return
  1202. }
  1203. t, err := time.Parse(FormatDateWallWithLoc, originalString)
  1204. if err != nil {
  1205. fmt.Println("Error parsing time:", err)
  1206. return
  1207. }
  1208. formatStr = t.Format(FormatDate)
  1209. return
  1210. }