libString.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package lib
  2. import (
  3. "errors"
  4. "math/rand"
  5. "regexp"
  6. "strings"
  7. "time"
  8. )
  9. // #取得随机字符串:通过打乱slice来操作
  10. func GetRandstring(length int, char string, rand_x int64) string {
  11. if length < 1 {
  12. return ""
  13. }
  14. if len(char) <= 6 || len(char) <= length {
  15. char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  16. }
  17. charArr := strings.Split(char, "")
  18. ran := rand.New(rand.NewSource(time.Now().UnixMilli() + rand_x))
  19. l := len(charArr)
  20. for i := l - 1; i > 0; i-- {
  21. r := ran.Intn(i)
  22. charArr[r], charArr[i] = charArr[i], charArr[r]
  23. }
  24. rchar := charArr[:length]
  25. return strings.Join(rchar, "")
  26. }
  27. // 检查日期格式
  28. func IsDateStr(date string) bool {
  29. if _, err := time.Parse("2006-01-02", date); err != nil {
  30. return false
  31. }
  32. return true
  33. }
  34. // 转化
  35. func TimeStrToTime(T_time string) (time.Time, bool) {
  36. stamp, err := time.ParseInLocation("2006-01-02 15:04:05", T_time, time.Local) // +8
  37. if err != nil {
  38. return time.Time{}, false
  39. }
  40. return stamp, true
  41. }
  42. func ReplaceSeconds(timeStr string) (string, error) {
  43. length := len(timeStr)
  44. if length < 2 {
  45. return "", errors.New("时间格式不正确")
  46. }
  47. lastTwoDigits := timeStr[length-2:]
  48. if lastTwoDigits == "00" {
  49. return timeStr, nil
  50. }
  51. t, err := time.Parse("2006-01-02 15:04:05", timeStr)
  52. if err != nil {
  53. return "", err
  54. }
  55. roundedTime := t.Truncate(time.Minute) // 将时间截断到分钟级别
  56. roundedTimeString := roundedTime.Format("2006-01-02 15:04:00")
  57. return roundedTimeString, nil
  58. }
  59. // 判断字符串是否为纯数字
  60. func IsNumeric(str string) bool {
  61. // 定义一个正则表达式来匹配纯数字字符串
  62. re := regexp.MustCompile(`^\d+$`)
  63. return re.MatchString(str)
  64. }
  65. func SubtractStringLists(list1, list2 []string) []string {
  66. // Create a map to store elements of list2 for fast lookup
  67. excludeMap := make(map[string]bool)
  68. for _, item := range list2 {
  69. excludeMap[item] = true
  70. }
  71. // Initialize the result slice with elements not present in list2
  72. var result []string
  73. for _, item := range list1 {
  74. if !excludeMap[item] {
  75. result = append(result, item)
  76. }
  77. }
  78. return result
  79. }