common.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "image"
  11. "image/png"
  12. "math"
  13. "math/rand"
  14. "net"
  15. "os"
  16. "os/exec"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "time"
  21. )
  22. //随机数种子
  23. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  24. func GetRandString(size int) string {
  25. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  26. randomSb := ""
  27. digitSize := len(allLetterDigit)
  28. for i := 0; i < size; i++ {
  29. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  30. }
  31. return randomSb
  32. }
  33. func GetRandStringNoSpecialChar(size int) string {
  34. allLetterDigit := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
  35. randomSb := ""
  36. digitSize := len(allLetterDigit)
  37. for i := 0; i < size; i++ {
  38. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  39. }
  40. return randomSb
  41. }
  42. func StringsToJSON(str string) string {
  43. rs := []rune(str)
  44. jsons := ""
  45. for _, r := range rs {
  46. rint := int(r)
  47. if rint < 128 {
  48. jsons += string(r)
  49. } else {
  50. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  51. }
  52. }
  53. return jsons
  54. }
  55. //序列化
  56. func ToString(v interface{}) string {
  57. data, _ := json.Marshal(v)
  58. return string(data)
  59. }
  60. //md5加密
  61. func MD5(data string) string {
  62. m := md5.Sum([]byte(data))
  63. return hex.EncodeToString(m[:])
  64. }
  65. // 获取数字随机字符
  66. func GetRandDigit(n int) string {
  67. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  68. }
  69. // 获取随机数
  70. func GetRandNumber(n int) int {
  71. return rnd.Intn(n)
  72. }
  73. func GetRandInt(min, max int) int {
  74. if min >= max || min == 0 || max == 0 {
  75. return max
  76. }
  77. return rand.Intn(max-min) + min
  78. }
  79. func GetToday(format string) string {
  80. today := time.Now().Format(format)
  81. return today
  82. }
  83. //获取今天剩余秒数
  84. func GetTodayLastSecond() time.Duration {
  85. today := GetToday(FormatDate) + " 23:59:59"
  86. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  87. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  88. }
  89. // 处理出生日期函数
  90. func GetBrithDate(idcard string) string {
  91. l := len(idcard)
  92. var s string
  93. if l == 15 {
  94. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  95. return s
  96. }
  97. if l == 18 {
  98. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  99. return s
  100. }
  101. return GetToday(FormatDate)
  102. }
  103. //处理性别
  104. func WhichSexByIdcard(idcard string) string {
  105. var sexs = [2]string{"女", "男"}
  106. length := len(idcard)
  107. if length == 18 {
  108. sex, _ := strconv.Atoi(string(idcard[16]))
  109. return sexs[sex%2]
  110. } else if length == 15 {
  111. sex, _ := strconv.Atoi(string(idcard[14]))
  112. return sexs[sex%2]
  113. }
  114. return "男"
  115. }
  116. //截取小数点后几位
  117. func SubFloatToString(f float64, m int) string {
  118. n := strconv.FormatFloat(f, 'f', -1, 64)
  119. if n == "" {
  120. return ""
  121. }
  122. if m >= len(n) {
  123. return n
  124. }
  125. newn := strings.Split(n, ".")
  126. if m == 0 {
  127. return newn[0]
  128. }
  129. if len(newn) < 2 || m >= len(newn[1]) {
  130. return n
  131. }
  132. return newn[0] + "." + newn[1][:m]
  133. }
  134. //截取小数点后几位
  135. func SubFloatToFloat(f float64, m int) float64 {
  136. newn := SubFloatToString(f, m)
  137. newf, _ := strconv.ParseFloat(newn, 64)
  138. return newf
  139. }
  140. //获取相差时间-年
  141. func GetYearDiffer(start_time, end_time string) int {
  142. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  143. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  144. age := t2.Year() - t1.Year()
  145. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  146. age--
  147. }
  148. return age
  149. }
  150. //获取相差时间-秒
  151. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  152. diff := end_time.Unix() - start_time.Unix()
  153. return diff
  154. }
  155. func FixFloat(f float64, m int) float64 {
  156. newn := SubFloatToString(f+0.00000001, m)
  157. newf, _ := strconv.ParseFloat(newn, 64)
  158. return newf
  159. }
  160. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  161. func StrListToString(strList []string) (str string) {
  162. if len(strList) > 0 {
  163. for k, v := range strList {
  164. if k == 0 {
  165. str = v
  166. } else {
  167. str = str + "," + v
  168. }
  169. }
  170. return
  171. }
  172. return ""
  173. }
  174. //Token
  175. func GetToken() string {
  176. randStr := GetRandString(64)
  177. token := MD5(randStr + Md5Key)
  178. tokenLen := 64 - len(token)
  179. return strings.ToUpper(token + GetRandString(tokenLen))
  180. }
  181. //数据没有记录
  182. func ErrNoRow() string {
  183. return "<QuerySeter> no row found"
  184. }
  185. //校验邮箱格式
  186. func ValidateEmailFormatat(email string) bool {
  187. reg := regexp.MustCompile(RegularEmail)
  188. return reg.MatchString(email)
  189. }
  190. //验证是否是手机号
  191. func ValidateMobileFormatat(mobileNum string) bool {
  192. reg := regexp.MustCompile(RegularMobile)
  193. return reg.MatchString(mobileNum)
  194. }
  195. //判断文件是否存在
  196. func FileIsExist(filePath string) bool {
  197. _, err := os.Stat(filePath)
  198. return err == nil || os.IsExist(err)
  199. }
  200. //获取图片扩展名
  201. func GetImgExt(file string) (ext string, err error) {
  202. var headerByte []byte
  203. headerByte = make([]byte, 8)
  204. fd, err := os.Open(file)
  205. if err != nil {
  206. return "", err
  207. }
  208. defer fd.Close()
  209. _, err = fd.Read(headerByte)
  210. if err != nil {
  211. return "", err
  212. }
  213. xStr := fmt.Sprintf("%x", headerByte)
  214. switch {
  215. case xStr == "89504e470d0a1a0a":
  216. ext = ".png"
  217. case xStr == "0000010001002020":
  218. ext = ".ico"
  219. case xStr == "0000020001002020":
  220. ext = ".cur"
  221. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  222. ext = ".gif"
  223. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  224. ext = ".tga"
  225. case xStr[:8] == "464f524d":
  226. ext = ".iff"
  227. case xStr[:8] == "52494646":
  228. ext = ".ani"
  229. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  230. ext = ".tiff"
  231. case xStr[:4] == "424d":
  232. ext = ".bmp"
  233. case xStr[:4] == "ffd8":
  234. ext = ".jpg"
  235. case xStr[:2] == "0a":
  236. ext = ".pcx"
  237. default:
  238. ext = ""
  239. }
  240. return ext, nil
  241. }
  242. //保存图片
  243. func SaveImage(path string, img image.Image) (err error) {
  244. //需要保持的文件
  245. imgfile, err := os.Create(path)
  246. defer imgfile.Close()
  247. // 以PNG格式保存文件
  248. err = png.Encode(imgfile, img)
  249. return err
  250. }
  251. //保存base64数据为文件
  252. func SaveBase64ToFile(content, path string) error {
  253. data, err := base64.StdEncoding.DecodeString(content)
  254. if err != nil {
  255. return err
  256. }
  257. f, err := os.Create(path)
  258. defer f.Close()
  259. if err != nil {
  260. return err
  261. }
  262. f.Write(data)
  263. return nil
  264. }
  265. func SaveBase64ToFileBySeek(content, path string) (err error) {
  266. data, err := base64.StdEncoding.DecodeString(content)
  267. exist, err := PathExists(path)
  268. if err != nil {
  269. return
  270. }
  271. if !exist {
  272. f, err := os.Create(path)
  273. if err != nil {
  274. return err
  275. }
  276. n, _ := f.Seek(0, 2)
  277. // 从末尾的偏移量开始写入内容
  278. _, err = f.WriteAt([]byte(data), n)
  279. defer f.Close()
  280. } else {
  281. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  282. if err != nil {
  283. return err
  284. }
  285. n, _ := f.Seek(0, 2)
  286. // 从末尾的偏移量开始写入内容
  287. _, err = f.WriteAt([]byte(data), n)
  288. defer f.Close()
  289. }
  290. return nil
  291. }
  292. func PathExists(path string) (bool, error) {
  293. _, err := os.Stat(path)
  294. if err == nil {
  295. return true, nil
  296. }
  297. if os.IsNotExist(err) {
  298. return false, nil
  299. }
  300. return false, err
  301. }
  302. func StartIndex(page, pagesize int) int {
  303. if page > 1 {
  304. return (page - 1) * pagesize
  305. }
  306. return 0
  307. }
  308. func PageCount(count, pagesize int) int {
  309. if count%pagesize > 0 {
  310. return count/pagesize + 1
  311. } else {
  312. return count / pagesize
  313. }
  314. }
  315. func TrimHtml(src string) string {
  316. //将HTML标签全转换成小写
  317. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  318. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  319. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  320. src = re.ReplaceAllString(src, "[图片]")
  321. re, _ = regexp.Compile("class[\\S\\s]+?>")
  322. src = re.ReplaceAllString(src, "")
  323. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  324. src = re.ReplaceAllString(src, "")
  325. return strings.TrimSpace(src)
  326. }
  327. //1556164246 -> 2019-04-25 03:50:46 +0000
  328. //timestamp
  329. func TimeToTimestamp() {
  330. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  331. }
  332. func ToUnicode(text string) string {
  333. textQuoted := strconv.QuoteToASCII(text)
  334. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  335. return textUnquoted
  336. }
  337. func VersionToInt(version string) int {
  338. version = strings.Replace(version, ".", "", -1)
  339. n, _ := strconv.Atoi(version)
  340. return n
  341. }
  342. func IsCheckInList(list []int, s int) bool {
  343. for _, v := range list {
  344. if v == s {
  345. return true
  346. }
  347. }
  348. return false
  349. }
  350. func round(num float64) int {
  351. return int(num + math.Copysign(0.5, num))
  352. }
  353. func toFixed(num float64, precision int) float64 {
  354. output := math.Pow(10, float64(precision))
  355. return float64(round(num*output)) / output
  356. }
  357. // GetWilsonScore returns Wilson Score
  358. func GetWilsonScore(p, n float64) float64 {
  359. if p == 0 && n == 0 {
  360. return 0
  361. }
  362. 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)
  363. }
  364. //将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  365. func ChangeWordsToNum(str string) (numStr string) {
  366. words := ([]rune)(str)
  367. num := 0
  368. n := 0
  369. for i := 0; i < len(words); i++ {
  370. word := string(words[i : i+1])
  371. switch word {
  372. case "万":
  373. if n == 0 {
  374. n = 1
  375. }
  376. n = n * 10000
  377. num = num*10000 + n
  378. n = 0
  379. case "千":
  380. if n == 0 {
  381. n = 1
  382. }
  383. n = n * 1000
  384. num += n
  385. n = 0
  386. case "百":
  387. if n == 0 {
  388. n = 1
  389. }
  390. n = n * 100
  391. num += n
  392. n = 0
  393. case "十":
  394. if n == 0 {
  395. n = 1
  396. }
  397. n = n * 10
  398. num += n
  399. n = 0
  400. case "一":
  401. n += 1
  402. case "二":
  403. n += 2
  404. case "三":
  405. n += 3
  406. case "四":
  407. n += 4
  408. case "五":
  409. n += 5
  410. case "六":
  411. n += 6
  412. case "七":
  413. n += 7
  414. case "八":
  415. n += 8
  416. case "九":
  417. n += 9
  418. case "零":
  419. default:
  420. if n > 0 {
  421. num += n
  422. n = 0
  423. }
  424. if num == 0 {
  425. numStr += word
  426. } else {
  427. numStr += strconv.Itoa(num) + word
  428. num = 0
  429. }
  430. }
  431. }
  432. if n > 0 {
  433. num += n
  434. n = 0
  435. }
  436. if num != 0 {
  437. numStr += strconv.Itoa(num)
  438. }
  439. return
  440. }
  441. func Sha1(data string) string {
  442. sha1 := sha1.New()
  443. sha1.Write([]byte(data))
  444. return hex.EncodeToString(sha1.Sum([]byte("")))
  445. }
  446. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  447. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  448. out, err := exec.Command("bash", "-c", cmd).Output()
  449. if err != nil {
  450. return
  451. }
  452. outTimes := string(out)
  453. //fmt.Println("outTimes:", outTimes)
  454. if outTimes != "" {
  455. timeArr := strings.Split(outTimes, ":")
  456. h := timeArr[0]
  457. m := timeArr[1]
  458. s := timeArr[2]
  459. hInt, err := strconv.Atoi(h)
  460. if err != nil {
  461. return playSeconds, err
  462. }
  463. mInt, err := strconv.Atoi(m)
  464. if err != nil {
  465. return playSeconds, err
  466. }
  467. s = strings.Trim(s, " ")
  468. s = strings.Trim(s, "\n")
  469. sInt, err := strconv.ParseFloat(s, 64)
  470. if err != nil {
  471. return playSeconds, err
  472. }
  473. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  474. }
  475. return
  476. }
  477. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  478. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  479. tradeCode = strings.Trim(tradeCode, " ")
  480. tradeCodeInt, err := strconv.Atoi(tradeCode)
  481. if err != nil {
  482. return
  483. }
  484. tradeCodeInt = tradeCodeInt + 1
  485. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  486. return
  487. }
  488. // excel日期字段格式化 yyyy-mm-dd
  489. func ConvertToFormatDay(excelDaysString string) string {
  490. // 2006-01-02 距离 1900-01-01的天数
  491. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  492. curDiffDay := excelDaysString
  493. b, _ := strconv.Atoi(curDiffDay)
  494. // 获取excel的日期距离2006-01-02的天数
  495. realDiffDay := b - baseDiffDay
  496. //fmt.Println("realDiffDay:",realDiffDay)
  497. // 距离2006-01-02 秒数
  498. realDiffSecond := realDiffDay * 24 * 3600
  499. //fmt.Println("realDiffSecond:",realDiffSecond)
  500. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  501. baseOriginSecond := 1136185445
  502. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  503. return resultTime
  504. }
  505. //人民币小写转大写
  506. func ConvertNumToCny(num float64) (str string, err error) {
  507. strNum := strconv.FormatFloat(num*100, 'f', 0, 64)
  508. sliceUnit := []string{"仟", "佰", "拾", "亿", "仟", "佰", "拾", "万", "仟", "佰", "拾", "元", "角", "分"}
  509. // log.Println(sliceUnit[:len(sliceUnit)-2])
  510. s := sliceUnit[len(sliceUnit)-len(strNum):]
  511. upperDigitUnit := map[string]string{"0": "零", "1": "壹", "2": "贰", "3": "叁", "4": "肆", "5": "伍", "6": "陆", "7": "柒", "8": "捌", "9": "玖"}
  512. for k, v := range strNum[:] {
  513. str = str + upperDigitUnit[string(v)] + s[k]
  514. }
  515. reg, err := regexp.Compile(`零角零分$`)
  516. str = reg.ReplaceAllString(str, "整")
  517. reg, err = regexp.Compile(`零角`)
  518. str = reg.ReplaceAllString(str, "零")
  519. reg, err = regexp.Compile(`零分$`)
  520. str = reg.ReplaceAllString(str, "整")
  521. reg, err = regexp.Compile(`零[仟佰拾]`)
  522. str = reg.ReplaceAllString(str, "零")
  523. reg, err = regexp.Compile(`零{2,}`)
  524. str = reg.ReplaceAllString(str, "零")
  525. reg, err = regexp.Compile(`零亿`)
  526. str = reg.ReplaceAllString(str, "亿")
  527. reg, err = regexp.Compile(`零万`)
  528. str = reg.ReplaceAllString(str, "万")
  529. reg, err = regexp.Compile(`零*元`)
  530. str = reg.ReplaceAllString(str, "元")
  531. reg, err = regexp.Compile(`亿零{0, 3}万`)
  532. str = reg.ReplaceAllString(str, "^元")
  533. reg, err = regexp.Compile(`零元`)
  534. str = reg.ReplaceAllString(str, "零")
  535. return
  536. }
  537. // CalculationDate 计算两个日期之间相差n年m月y天
  538. func CalculationDate(startDate, endDate time.Time) (beetweenDay string, err error) {
  539. //startDate := time.Date(2021, 3, 28, 0, 0, 0, 0, time.Now().Location())
  540. //endDate := time.Date(2022, 3, 31, 0, 0, 0, 0, time.Now().Location())
  541. numYear := endDate.Year() - startDate.Year()
  542. numMonth := int(endDate.Month()) - int(startDate.Month())
  543. numDay := 0
  544. //获取截止月的总天数
  545. endDateDays := getMonthDay(endDate.Year(), int(endDate.Month()))
  546. //获取截止月的前一个月
  547. endDatePrevMonthDate := endDate.AddDate(0, -1, 0)
  548. //获取截止日期的上一个月的总天数
  549. endDatePrevMonthDays := getMonthDay(endDatePrevMonthDate.Year(), int(endDatePrevMonthDate.Month()))
  550. //获取开始日期的的月份总天数
  551. startDateMonthDays := getMonthDay(startDate.Year(), int(startDate.Month()))
  552. //判断,截止月是否完全被选中,如果相等,那么代表截止月份全部天数被选择
  553. if endDate.Day() == endDateDays {
  554. numDay = startDateMonthDays - startDate.Day() + 1
  555. //如果剩余天数正好与开始日期的天数是一致的,那么月份加1
  556. if numDay == startDateMonthDays {
  557. numMonth++
  558. numDay = 0
  559. //超过月份了,那么年份加1
  560. if numMonth == 12 {
  561. numYear++
  562. numMonth = 0
  563. }
  564. }
  565. } else {
  566. numDay = endDate.Day() - startDate.Day() + 1
  567. }
  568. //天数小于0,那么向月份借一位
  569. if numDay < 0 {
  570. //向上一个月借一个月的天数
  571. numDay += endDatePrevMonthDays
  572. //总月份减去一个月
  573. numMonth = numMonth - 1
  574. }
  575. //月份小于0,那么向年份借一位
  576. if numMonth < 0 {
  577. //向上一个年借12个月
  578. numMonth += 12
  579. //总年份减去一年
  580. numYear = numYear - 1
  581. }
  582. if numYear < 0 {
  583. err = errors.New("日期异常")
  584. return
  585. }
  586. if numYear > 0 {
  587. beetweenDay += fmt.Sprint(numYear, "年")
  588. }
  589. if numMonth > 0 {
  590. beetweenDay += fmt.Sprint(numMonth, "个月")
  591. }
  592. if numDay > 0 {
  593. beetweenDay += fmt.Sprint(numDay, "天")
  594. }
  595. return
  596. }
  597. // getMonthDay 获取某年某月有多少天
  598. func getMonthDay(year, month int) (days int) {
  599. if month != 2 {
  600. if month == 4 || month == 6 || month == 9 || month == 11 {
  601. days = 30
  602. } else {
  603. days = 31
  604. }
  605. } else {
  606. if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
  607. days = 29
  608. } else {
  609. days = 28
  610. }
  611. }
  612. return
  613. }
  614. //字符串转换为time
  615. func StrTimeToTime(strTime string) time.Time {
  616. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  617. loc, _ := time.LoadLocation("Local") //重要:获取时区
  618. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  619. return resultTime
  620. }
  621. // InArray 是否在切片(数组/map)中含有该值,目前只支持:string、int 、 int64,其他都是返回false
  622. func InArray(needle interface{}, hyStack interface{}) bool {
  623. switch key := needle.(type) {
  624. case string:
  625. for _, item := range hyStack.([]string) {
  626. if key == item {
  627. return true
  628. }
  629. }
  630. case int:
  631. for _, item := range hyStack.([]int) {
  632. if key == item {
  633. return true
  634. }
  635. }
  636. case int64:
  637. for _, item := range hyStack.([]int64) {
  638. if key == item {
  639. return true
  640. }
  641. }
  642. default:
  643. return false
  644. }
  645. return false
  646. }
  647. func GetLocalIP() (ip string, err error) {
  648. addrs, err := net.InterfaceAddrs()
  649. if err != nil {
  650. return
  651. }
  652. for _, addr := range addrs {
  653. ipAddr, ok := addr.(*net.IPNet)
  654. if !ok {
  655. continue
  656. }
  657. if ipAddr.IP.IsLoopback() {
  658. continue
  659. }
  660. if !ipAddr.IP.IsGlobalUnicast() {
  661. continue
  662. }
  663. return ipAddr.IP.String(), nil
  664. }
  665. return
  666. }
  667. // TrimStr 移除字符串中的空格
  668. func TrimStr(str string) (str2 string) {
  669. if str == "" {
  670. return str
  671. }
  672. return strings.Replace(str, " ", "", -1)
  673. }
  674. // GetOrmInReplace 获取orm的in查询替换?的方法
  675. func GetOrmInReplace(num int) string {
  676. template := make([]string, num)
  677. for i := 0; i < num; i++ {
  678. template[i] = "?"
  679. }
  680. return strings.Join(template, ",")
  681. }