common.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "image"
  10. "image/png"
  11. "math"
  12. "math/rand"
  13. "net"
  14. "os"
  15. "os/exec"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. "time"
  20. )
  21. // 随机数种子
  22. var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
  23. func GetRandString(size int) string {
  24. 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", "!", "@", "#", "$", "%", "^", "&", "*"}
  25. randomSb := ""
  26. digitSize := len(allLetterDigit)
  27. for i := 0; i < size; i++ {
  28. randomSb += allLetterDigit[rnd.Intn(digitSize)]
  29. }
  30. return randomSb
  31. }
  32. func GetRandStringNoSpecialChar(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 StringsToJSON(str string) string {
  42. rs := []rune(str)
  43. jsons := ""
  44. for _, r := range rs {
  45. rint := int(r)
  46. if rint < 128 {
  47. jsons += string(r)
  48. } else {
  49. jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
  50. }
  51. }
  52. return jsons
  53. }
  54. // 序列化
  55. func ToString(v interface{}) string {
  56. data, _ := json.Marshal(v)
  57. return string(data)
  58. }
  59. // md5加密
  60. func MD5(data string) string {
  61. m := md5.Sum([]byte(data))
  62. return hex.EncodeToString(m[:])
  63. }
  64. // md5加密
  65. func Get16MD5Encode(data string) string {
  66. m := md5.Sum([]byte(data))
  67. encodehex := hex.EncodeToString(m[:])
  68. return encodehex[8:24]
  69. }
  70. // 获取数字随机字符
  71. func GetRandDigit(n int) string {
  72. return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
  73. }
  74. // 获取随机数
  75. func GetRandNumber(n int) int {
  76. return rnd.Intn(n)
  77. }
  78. func GetRandInt(min, max int) int {
  79. if min >= max || min == 0 || max == 0 {
  80. return max
  81. }
  82. return rand.Intn(max-min) + min
  83. }
  84. func GetToday(format string) string {
  85. today := time.Now().Format(format)
  86. return today
  87. }
  88. // 获取今天剩余秒数
  89. func GetTodayLastSecond() time.Duration {
  90. today := GetToday(FormatDate) + " 23:59:59"
  91. end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
  92. return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
  93. }
  94. // 处理出生日期函数
  95. func GetBrithDate(idcard string) string {
  96. l := len(idcard)
  97. var s string
  98. if l == 15 {
  99. s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
  100. return s
  101. }
  102. if l == 18 {
  103. s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
  104. return s
  105. }
  106. return GetToday(FormatDate)
  107. }
  108. // 处理性别
  109. func WhichSexByIdcard(idcard string) string {
  110. var sexs = [2]string{"女", "男"}
  111. length := len(idcard)
  112. if length == 18 {
  113. sex, _ := strconv.Atoi(string(idcard[16]))
  114. return sexs[sex%2]
  115. } else if length == 15 {
  116. sex, _ := strconv.Atoi(string(idcard[14]))
  117. return sexs[sex%2]
  118. }
  119. return "男"
  120. }
  121. // 截取小数点后几位
  122. func SubFloatToString(f float64, m int) string {
  123. n := strconv.FormatFloat(f, 'f', -1, 64)
  124. if n == "" {
  125. return ""
  126. }
  127. if m >= len(n) {
  128. return n
  129. }
  130. newn := strings.Split(n, ".")
  131. if m == 0 {
  132. return newn[0]
  133. }
  134. if len(newn) < 2 || m >= len(newn[1]) {
  135. return n
  136. }
  137. return newn[0] + "." + newn[1][:m]
  138. }
  139. // 截取小数点后几位
  140. func SubFloatToFloat(f float64, m int) float64 {
  141. newn := SubFloatToString(f, m)
  142. newf, _ := strconv.ParseFloat(newn, 64)
  143. return newf
  144. }
  145. // 获取相差时间-年
  146. func GetYearDiffer(start_time, end_time string) int {
  147. t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
  148. t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
  149. age := t2.Year() - t1.Year()
  150. if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
  151. age--
  152. }
  153. return age
  154. }
  155. // 获取相差时间-秒
  156. func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
  157. diff := end_time.Unix() - start_time.Unix()
  158. return diff
  159. }
  160. func FixFloat(f float64, m int) float64 {
  161. newn := SubFloatToString(f+0.00000001, m)
  162. newf, _ := strconv.ParseFloat(newn, 64)
  163. return newf
  164. }
  165. // 将字符串数组转化为逗号分割的字符串形式 ["str1","str2","str3"] >>> "str1,str2,str3"
  166. func StrListToString(strList []string) (str string) {
  167. if len(strList) > 0 {
  168. for k, v := range strList {
  169. if k == 0 {
  170. str = v
  171. } else {
  172. str = str + "," + v
  173. }
  174. }
  175. return
  176. }
  177. return ""
  178. }
  179. // Token
  180. func GetToken() string {
  181. randStr := GetRandString(64)
  182. token := MD5(randStr + Md5Key)
  183. tokenLen := 64 - len(token)
  184. return strings.ToUpper(token + GetRandString(tokenLen))
  185. }
  186. // 数据没有记录
  187. func ErrNoRow() string {
  188. return "<QuerySeter> no row found"
  189. }
  190. // 校验邮箱格式
  191. func ValidateEmailFormatat(email string) bool {
  192. reg := regexp.MustCompile(RegularEmail)
  193. return reg.MatchString(email)
  194. }
  195. // 验证是否是手机号
  196. func ValidateMobileFormatat(mobileNum string) bool {
  197. reg := regexp.MustCompile(RegularMobile)
  198. return reg.MatchString(mobileNum)
  199. }
  200. // 验证是否是固定电话
  201. func ValidateFixedTelephoneFormatat(mobileNum string) bool {
  202. reg := regexp.MustCompile(RegularFixedTelephone)
  203. return reg.MatchString(mobileNum)
  204. }
  205. // 验证是否是固定电话宽松
  206. func ValidateFixedTelephoneFormatatEasy(mobileNum string) bool {
  207. reg := regexp.MustCompile(RegularFixedTelephoneEasy)
  208. return reg.MatchString(mobileNum)
  209. }
  210. // 判断文件是否存在
  211. func FileIsExist(filePath string) bool {
  212. _, err := os.Stat(filePath)
  213. return err == nil || os.IsExist(err)
  214. }
  215. // 获取图片扩展名
  216. func GetImgExt(file string) (ext string, err error) {
  217. var headerByte []byte
  218. headerByte = make([]byte, 8)
  219. fd, err := os.Open(file)
  220. if err != nil {
  221. return "", err
  222. }
  223. defer fd.Close()
  224. _, err = fd.Read(headerByte)
  225. if err != nil {
  226. return "", err
  227. }
  228. xStr := fmt.Sprintf("%x", headerByte)
  229. switch {
  230. case xStr == "89504e470d0a1a0a":
  231. ext = ".png"
  232. case xStr == "0000010001002020":
  233. ext = ".ico"
  234. case xStr == "0000020001002020":
  235. ext = ".cur"
  236. case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
  237. ext = ".gif"
  238. case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
  239. ext = ".tga"
  240. case xStr[:8] == "464f524d":
  241. ext = ".iff"
  242. case xStr[:8] == "52494646":
  243. ext = ".ani"
  244. case xStr[:4] == "4d4d" || xStr[:4] == "4949":
  245. ext = ".tiff"
  246. case xStr[:4] == "424d":
  247. ext = ".bmp"
  248. case xStr[:4] == "ffd8":
  249. ext = ".jpg"
  250. case xStr[:2] == "0a":
  251. ext = ".pcx"
  252. default:
  253. ext = ""
  254. }
  255. return ext, nil
  256. }
  257. // 保存图片
  258. func SaveImage(path string, img image.Image) (err error) {
  259. //需要保持的文件
  260. imgfile, err := os.Create(path)
  261. defer imgfile.Close()
  262. // 以PNG格式保存文件
  263. err = png.Encode(imgfile, img)
  264. return err
  265. }
  266. // 保存base64数据为文件
  267. func SaveBase64ToFile(content, path string) error {
  268. data, err := base64.StdEncoding.DecodeString(content)
  269. if err != nil {
  270. return err
  271. }
  272. f, err := os.Create(path)
  273. defer f.Close()
  274. if err != nil {
  275. return err
  276. }
  277. f.Write(data)
  278. return nil
  279. }
  280. func SaveBase64ToFileBySeek(content, path string) (err error) {
  281. data, err := base64.StdEncoding.DecodeString(content)
  282. exist, err := PathExists(path)
  283. if err != nil {
  284. return
  285. }
  286. if !exist {
  287. f, err := os.Create(path)
  288. if err != nil {
  289. return err
  290. }
  291. n, _ := f.Seek(0, 2)
  292. // 从末尾的偏移量开始写入内容
  293. _, err = f.WriteAt([]byte(data), n)
  294. defer f.Close()
  295. } else {
  296. f, err := os.OpenFile(path, os.O_WRONLY, 0644)
  297. if err != nil {
  298. return err
  299. }
  300. n, _ := f.Seek(0, 2)
  301. // 从末尾的偏移量开始写入内容
  302. _, err = f.WriteAt([]byte(data), n)
  303. defer f.Close()
  304. }
  305. return nil
  306. }
  307. func PathExists(path string) (bool, error) {
  308. _, err := os.Stat(path)
  309. if err == nil {
  310. return true, nil
  311. }
  312. if os.IsNotExist(err) {
  313. return false, nil
  314. }
  315. return false, err
  316. }
  317. func StartIndex(page, pagesize int) int {
  318. if page > 1 {
  319. return (page - 1) * pagesize
  320. }
  321. return 0
  322. }
  323. func PageCount(count, pagesize int) int {
  324. if count%pagesize > 0 {
  325. return count/pagesize + 1
  326. } else {
  327. return count / pagesize
  328. }
  329. }
  330. func TrimHtml(src string) string {
  331. //将HTML标签全转换成小写
  332. re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
  333. src = re.ReplaceAllStringFunc(src, strings.ToLower)
  334. re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
  335. src = re.ReplaceAllString(src, "[图片]")
  336. re, _ = regexp.Compile("class[\\S\\s]+?>")
  337. src = re.ReplaceAllString(src, "")
  338. re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
  339. src = re.ReplaceAllString(src, "")
  340. return strings.TrimSpace(src)
  341. }
  342. //1556164246 -> 2019-04-25 03:50:46 +0000
  343. //timestamp
  344. func TimeToTimestamp() {
  345. fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
  346. }
  347. func ToUnicode(text string) string {
  348. textQuoted := strconv.QuoteToASCII(text)
  349. textUnquoted := textQuoted[1 : len(textQuoted)-1]
  350. return textUnquoted
  351. }
  352. func VersionToInt(version string) int {
  353. version = strings.Replace(version, ".", "", -1)
  354. n, _ := strconv.Atoi(version)
  355. return n
  356. }
  357. func IsCheckInList(list []int, s int) bool {
  358. for _, v := range list {
  359. if v == s {
  360. return true
  361. }
  362. }
  363. return false
  364. }
  365. func round(num float64) int {
  366. return int(num + math.Copysign(0.5, num))
  367. }
  368. func toFixed(num float64, precision int) float64 {
  369. output := math.Pow(10, float64(precision))
  370. return float64(round(num*output)) / output
  371. }
  372. // GetWilsonScore returns Wilson Score
  373. func GetWilsonScore(p, n float64) float64 {
  374. if p == 0 && n == 0 {
  375. return 0
  376. }
  377. 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)
  378. }
  379. // 将中文数字转化成数字,比如 第三百四十五章,返回第345章 不支持一亿及以上
  380. func ChangeWordsToNum(str string) (numStr string) {
  381. words := ([]rune)(str)
  382. num := 0
  383. n := 0
  384. for i := 0; i < len(words); i++ {
  385. word := string(words[i : i+1])
  386. switch word {
  387. case "万":
  388. if n == 0 {
  389. n = 1
  390. }
  391. n = n * 10000
  392. num = num*10000 + n
  393. n = 0
  394. case "千":
  395. if n == 0 {
  396. n = 1
  397. }
  398. n = n * 1000
  399. num += n
  400. n = 0
  401. case "百":
  402. if n == 0 {
  403. n = 1
  404. }
  405. n = n * 100
  406. num += n
  407. n = 0
  408. case "十":
  409. if n == 0 {
  410. n = 1
  411. }
  412. n = n * 10
  413. num += n
  414. n = 0
  415. case "一":
  416. n += 1
  417. case "二":
  418. n += 2
  419. case "三":
  420. n += 3
  421. case "四":
  422. n += 4
  423. case "五":
  424. n += 5
  425. case "六":
  426. n += 6
  427. case "七":
  428. n += 7
  429. case "八":
  430. n += 8
  431. case "九":
  432. n += 9
  433. case "零":
  434. default:
  435. if n > 0 {
  436. num += n
  437. n = 0
  438. }
  439. if num == 0 {
  440. numStr += word
  441. } else {
  442. numStr += strconv.Itoa(num) + word
  443. num = 0
  444. }
  445. }
  446. }
  447. if n > 0 {
  448. num += n
  449. n = 0
  450. }
  451. if num != 0 {
  452. numStr += strconv.Itoa(num)
  453. }
  454. return
  455. }
  456. func Sha1(data string) string {
  457. sha1 := sha1.New()
  458. sha1.Write([]byte(data))
  459. return hex.EncodeToString(sha1.Sum([]byte("")))
  460. }
  461. func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
  462. cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
  463. out, err := exec.Command("bash", "-c", cmd).Output()
  464. if err != nil {
  465. return
  466. }
  467. outTimes := string(out)
  468. fmt.Println("outTimes:", outTimes)
  469. if outTimes != "" {
  470. timeArr := strings.Split(outTimes, ":")
  471. h := timeArr[0]
  472. m := timeArr[1]
  473. s := timeArr[2]
  474. hInt, err := strconv.Atoi(h)
  475. if err != nil {
  476. return playSeconds, err
  477. }
  478. mInt, err := strconv.Atoi(m)
  479. if err != nil {
  480. return playSeconds, err
  481. }
  482. s = strings.Trim(s, " ")
  483. s = strings.Trim(s, "\n")
  484. sInt, err := strconv.ParseFloat(s, 64)
  485. if err != nil {
  486. return playSeconds, err
  487. }
  488. playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
  489. }
  490. return
  491. }
  492. func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
  493. tradeCode = strings.Replace(tradeCode, "W", "", -1)
  494. tradeCode = strings.Trim(tradeCode, " ")
  495. tradeCodeInt, err := strconv.Atoi(tradeCode)
  496. if err != nil {
  497. return
  498. }
  499. tradeCodeInt = tradeCodeInt + 1
  500. maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
  501. return
  502. }
  503. // excel日期字段格式化 yyyy-mm-dd
  504. func ConvertToFormatDay(excelDaysString string) string {
  505. // 2006-01-02 距离 1900-01-01的天数
  506. baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
  507. curDiffDay := excelDaysString
  508. b, _ := strconv.Atoi(curDiffDay)
  509. // 获取excel的日期距离2006-01-02的天数
  510. realDiffDay := b - baseDiffDay
  511. //fmt.Println("realDiffDay:",realDiffDay)
  512. // 距离2006-01-02 秒数
  513. realDiffSecond := realDiffDay * 24 * 3600
  514. //fmt.Println("realDiffSecond:",realDiffSecond)
  515. // 2006-01-02 15:04:05距离1970-01-01 08:00:00的秒数 网上工具可查出
  516. baseOriginSecond := 1136185445
  517. resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
  518. return resultTime
  519. }
  520. // 字符串转换为time
  521. func StrTimeToTime(strTime string) time.Time {
  522. timeLayout := "2006-01-02 15:04:05" //转化所需模板
  523. loc, _ := time.LoadLocation("Local") //重要:获取时区
  524. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  525. return resultTime
  526. }
  527. // 时间格式去掉时分秒
  528. func TimeRemoveHms(strTime string) string {
  529. var Ymd string
  530. var resultTime = StrTimeToTime(strTime)
  531. year := resultTime.Year()
  532. month := resultTime.Format("01")
  533. day1 := resultTime.Day()
  534. if day1 < 10 {
  535. Ymd = strconv.Itoa(year) + "." + month + ".0" + strconv.Itoa(day1)
  536. } else {
  537. Ymd = strconv.Itoa(year) + "." + month + "." + strconv.Itoa(day1)
  538. }
  539. return Ymd
  540. }
  541. // 时间格式去掉时分秒
  542. func TimeRemoveHms2(strTime string) string {
  543. var Ymd string
  544. var resultTime = StrTimeToTime(strTime)
  545. year := resultTime.Year()
  546. month := resultTime.Format("01")
  547. day1 := resultTime.Day()
  548. if day1 < 10 {
  549. Ymd = strconv.Itoa(year) + "-" + month + "-0" + strconv.Itoa(day1)
  550. } else {
  551. Ymd = strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day1)
  552. }
  553. return Ymd
  554. }
  555. // 判断时间是当年的第几周
  556. func WeekByDate(t time.Time) string {
  557. var resultSAtr string
  558. //t = t.AddDate(0, 0, -8) // 减少八天跟老数据标题统一
  559. yearDay := t.YearDay()
  560. yearFirstDay := t.AddDate(0, 0, -yearDay+1)
  561. firstDayInWeek := int(yearFirstDay.Weekday())
  562. //今年第一周有几天
  563. firstWeekDays := 1
  564. if firstDayInWeek != 0 {
  565. firstWeekDays = 7 - firstDayInWeek + 1
  566. }
  567. var week int
  568. if yearDay <= firstWeekDays {
  569. week = 1
  570. } else {
  571. week = (yearDay-firstWeekDays)/7 + 2
  572. }
  573. resultSAtr = "(" + strconv.Itoa(t.Year()) + "年第" + strconv.Itoa(week) + "周" + ")"
  574. return resultSAtr
  575. }
  576. func Mp3Time(videoPlaySeconds string) string {
  577. var d int
  578. var timeStr string
  579. a, _ := strconv.ParseFloat(videoPlaySeconds, 32)
  580. b := int(a)
  581. if b <= 60 {
  582. timeStr = "00:" + strconv.Itoa(b)
  583. } else {
  584. c := b % 60
  585. d = b / 60
  586. if d < 10 {
  587. timeStr = "0" + strconv.Itoa(d) + ":" + strconv.Itoa(c)
  588. } else {
  589. timeStr = strconv.Itoa(d) + ":" + strconv.Itoa(c)
  590. }
  591. }
  592. return timeStr
  593. }
  594. // 用户参会时间转换
  595. func GetAttendanceDetailSeconds(secondNum int) string {
  596. var timeStr string
  597. if secondNum <= 60 {
  598. if secondNum < 10 {
  599. timeStr = "0" + strconv.Itoa(secondNum) + "''"
  600. } else {
  601. timeStr = strconv.Itoa(secondNum) + "''"
  602. }
  603. } else {
  604. var remainderStr string
  605. remainderNum := secondNum % 60
  606. minuteNum := secondNum / 60
  607. if remainderNum < 10 {
  608. remainderStr = "0" + strconv.Itoa(remainderNum) + "''"
  609. } else {
  610. remainderStr = strconv.Itoa(remainderNum) + "''"
  611. }
  612. if minuteNum < 10 {
  613. timeStr = "0" + strconv.Itoa(minuteNum) + "'" + remainderStr
  614. } else {
  615. timeStr = strconv.Itoa(minuteNum) + "'" + remainderStr
  616. }
  617. }
  618. return timeStr
  619. }
  620. // 用户参会时间转换
  621. func GetAttendanceDetailSecondsByYiDong(str string) string {
  622. var timeStr string
  623. timeStr = strings.Replace(str, ":", "'", -1)
  624. timeStr += "''"
  625. return timeStr
  626. }
  627. // GetOrmInReplace 获取orm的in查询替换?的方法
  628. func GetOrmInReplace(num int) string {
  629. template := make([]string, num)
  630. for i := 0; i < num; i++ {
  631. template[i] = "?"
  632. }
  633. return strings.Join(template, ",")
  634. }
  635. func GetLocalIP() (ip string, err error) {
  636. addrs, err := net.InterfaceAddrs()
  637. if err != nil {
  638. return
  639. }
  640. for _, addr := range addrs {
  641. ipAddr, ok := addr.(*net.IPNet)
  642. if !ok {
  643. continue
  644. }
  645. if ipAddr.IP.IsLoopback() {
  646. continue
  647. }
  648. if !ipAddr.IP.IsGlobalUnicast() {
  649. continue
  650. }
  651. return ipAddr.IP.String(), nil
  652. }
  653. return
  654. }
  655. // 字符串类型时间转周几
  656. func StrDateTimeToWeek(strTime string) string {
  657. var WeekDayMap = map[string]string{
  658. "Monday": "周一",
  659. "Tuesday": "周二",
  660. "Wednesday": "周三",
  661. "Thursday": "周四",
  662. "Friday": "周五",
  663. "Saturday": "周六",
  664. "Sunday": "周日",
  665. }
  666. var ctime = StrTimeToTime(strTime).Format("2006-01-02")
  667. fmt.Println(ctime)
  668. startday, _ := time.Parse("2006-01-02", ctime)
  669. staweek_int := startday.Weekday().String()
  670. return WeekDayMap[staweek_int]
  671. }
  672. // ReplaceSpaceAndWrap 去除空格跟换行
  673. func ReplaceSpaceAndWrap(str string) string {
  674. // 去除空格
  675. str = strings.Replace(str, " ", "", -1)
  676. // 去除换行符
  677. str = strings.Replace(str, "\n", "", -1)
  678. return str
  679. }
  680. // InArrayByInt php中的in_array(判断Int类型的切片中是否存在该int值)
  681. func InArrayByInt(idIntList []int, searchId int) (has bool) {
  682. for _, id := range idIntList {
  683. if id == searchId {
  684. has = true
  685. return
  686. }
  687. }
  688. return
  689. }
  690. // InArrayByStr php中的in_array(判断String类型的切片中是否存在该string值)
  691. func InArrayByStr(idStrList []string, searchId string) (has bool) {
  692. for _, id := range idStrList {
  693. if id == searchId {
  694. has = true
  695. return
  696. }
  697. }
  698. return
  699. }
  700. // GetNowWeekMonday 获取本周周一的时间
  701. func GetNowWeekMonday() time.Time {
  702. offset := int(time.Monday - time.Now().Weekday())
  703. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  704. offset = -6
  705. }
  706. mondayTime := time.Now().AddDate(0, 0, offset)
  707. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  708. return mondayTime
  709. }
  710. // GetLastWeekMonday 获取上周周一的时间
  711. func GetLastWeekMonday() time.Time {
  712. offset := int(time.Monday - time.Now().Weekday())
  713. if offset == 1 { //正好是周日,但是按照中国人的理解,周日是一周最后一天,而不是一周开始的第一天
  714. offset = -6
  715. }
  716. mondayTime := time.Now().AddDate(0, 0, offset-7)
  717. mondayTime = time.Date(mondayTime.Year(), mondayTime.Month(), mondayTime.Day(), 0, 0, 0, 0, mondayTime.Location())
  718. return mondayTime
  719. }
  720. // GetNowWeekSunDay 获取本周周日的时间
  721. func GetNowWeekSunday() time.Time {
  722. return GetNowWeekMonday().AddDate(0, 0, 6)
  723. }
  724. // GetLastWeekSunday 获取上周周日的时间
  725. func GetLastWeekSunday() time.Time {
  726. return GetLastWeekMonday().AddDate(0, 0, 6)
  727. }
  728. // GetNowMonthFirstDay 获取本月第一天的时间
  729. func GetNowMonthFirstDay() time.Time {
  730. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location())
  731. return nowMonthFirstDay
  732. }
  733. // GetNowMonthLastDay 获取本月最后一天的时间
  734. func GetNowMonthLastDay() time.Time {
  735. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  736. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  737. return nowMonthLastDay
  738. }
  739. // GetNowMonthFirstDay 获取上月第一天的时间
  740. func GetLastMonthFirstDay() time.Time {
  741. nowMonthFirstDay := time.Date(time.Now().Year(), time.Now().AddDate(0, -1, 0).Month(), 1, 0, 0, 0, 0, time.Now().Location())
  742. return nowMonthFirstDay
  743. }
  744. // GetNowMonthLastDay 获取上月最后一天的时间
  745. func GetLastMonthLastDay() time.Time {
  746. nowMonthLastDay := time.Date(time.Now().Year(), time.Now().AddDate(0, -1, 0).Month(), 1, 0, 0, 0, 0, time.Now().Location()).AddDate(0, 1, -1)
  747. nowMonthLastDay = time.Date(nowMonthLastDay.Year(), nowMonthLastDay.Month(), nowMonthLastDay.Day(), 23, 59, 59, 0, nowMonthLastDay.Location())
  748. return nowMonthLastDay
  749. }
  750. // 字符串转换为time
  751. func StrDateToTime(strTime string) time.Time {
  752. timeLayout := "2006-01-02" //转化所需模板
  753. loc, _ := time.LoadLocation("Local") //重要:获取时区
  754. resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
  755. return resultTime
  756. }
  757. // 获取时间的月跟日
  758. func GetTimeDateHourAndDay(DayTime time.Time) (dataStr string) {
  759. dataSlice := strings.Split(DayTime.Format(FormatDate), "-")
  760. for k, v := range dataSlice {
  761. if k == 0 {
  762. continue
  763. }
  764. dataStr += v + "."
  765. }
  766. dataStr = strings.TrimRight(dataStr, ".")
  767. return
  768. }
  769. // 时间格式去掉年
  770. func GetTimeDateRemoveYear(strTime string) (dataStr string) {
  771. slicePublishTime := strings.Split(strTime, "-")
  772. for k, v := range slicePublishTime {
  773. if k == 0 {
  774. continue
  775. }
  776. dataStr += v + "-"
  777. }
  778. dataStr = strings.TrimRight(dataStr, "-")
  779. return dataStr
  780. }