libString.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package lib
  2. import (
  3. "fmt"
  4. "math"
  5. "math/rand"
  6. "regexp"
  7. "strings"
  8. "time"
  9. )
  10. // #取得随机字符串:通过打乱slice来操作
  11. func GetRandstring(length int, char string, rand_x int64) string {
  12. if length < 1 {
  13. return ""
  14. }
  15. if len(char) <= 6 || len(char) <= length {
  16. char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  17. }
  18. charArr := strings.Split(char, "")
  19. ran := rand.New(rand.NewSource(time.Now().UnixMilli() + rand_x))
  20. l := len(charArr)
  21. for i := l - 1; i > 0; i-- {
  22. r := ran.Intn(i)
  23. charArr[r], charArr[i] = charArr[i], charArr[r]
  24. }
  25. rchar := charArr[:length]
  26. return strings.Join(rchar, "")
  27. }
  28. // 检查日期格式
  29. func IsDateStr(date string) bool {
  30. if _, err := time.Parse("2006-01-02", date); err != nil {
  31. return false
  32. }
  33. return true
  34. }
  35. // 转化
  36. func TimeStrToTime(T_time string) (time.Time, bool) {
  37. stamp, err := time.ParseInLocation("2006-01-02 15:04:05", T_time, time.Local) // +8
  38. if err != nil {
  39. return time.Time{}, false
  40. }
  41. return stamp, true
  42. }
  43. func TimeStrToTime2(T_time string) (time.Time, bool) {
  44. stamp, err := time.ParseInLocation("2006-01-02 15:04:05", T_time, time.Local) // +8
  45. if err != nil {
  46. return time.Time{}, false
  47. }
  48. return stamp, true
  49. }
  50. // 判断字符串是否为纯数字
  51. func IsNumeric(str string) bool {
  52. // 定义一个正则表达式来匹配纯数字字符串
  53. re := regexp.MustCompile(`^\d+$`)
  54. return re.MatchString(str)
  55. }
  56. // 计算两个时间字符串之间的分钟差
  57. func MinutesDifference(startTime, endTime string) (float64, error) {
  58. layout := "2006-01-02 15:04:05"
  59. st, err := time.Parse(layout, startTime)
  60. if err != nil {
  61. return 0, fmt.Errorf("error parsing timeStr1: %w", err)
  62. }
  63. et, err := time.Parse(layout, endTime)
  64. if err != nil {
  65. return 0, fmt.Errorf("error parsing timeStr2: %w", err)
  66. }
  67. duration := et.Sub(st)
  68. minutes := math.Ceil(duration.Minutes())
  69. return minutes, nil
  70. }