libString.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package lib
  2. import (
  3. "errors"
  4. "math/rand"
  5. "strings"
  6. "time"
  7. )
  8. // #取得随机字符串:通过打乱slice来操作
  9. func GetRandstring(length int, char string, rand_x int64) string {
  10. if length < 1 {
  11. return ""
  12. }
  13. if len(char) <= 6 || len(char) <= length {
  14. char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  15. }
  16. charArr := strings.Split(char, "")
  17. ran := rand.New(rand.NewSource(time.Now().UnixMilli() + rand_x))
  18. l := len(charArr)
  19. for i := l - 1; i > 0; i-- {
  20. r := ran.Intn(i)
  21. charArr[r], charArr[i] = charArr[i], charArr[r]
  22. }
  23. rchar := charArr[:length]
  24. return strings.Join(rchar, "")
  25. }
  26. // 检查日期格式
  27. func IsDateStr(date string) bool {
  28. if _, err := time.Parse("2006-01-02", date); err != nil {
  29. return false
  30. }
  31. return true
  32. }
  33. // 转化
  34. func TimeStrToTime(T_time string) (time.Time, bool) {
  35. stamp, err := time.ParseInLocation("2006-01-02 15:04:05", T_time, time.Local) // +8
  36. if err != nil {
  37. return time.Time{}, false
  38. }
  39. return stamp, true
  40. }
  41. func ReplaceSeconds(timeStr string) (string, error) {
  42. length := len(timeStr)
  43. if length < 2 {
  44. return "", errors.New("时间格式不正确")
  45. }
  46. lastTwoDigits := timeStr[length-2:]
  47. if lastTwoDigits == "00" {
  48. return timeStr, nil
  49. }
  50. t, err := time.Parse("2006-01-02 15:04:05", timeStr)
  51. if err != nil {
  52. return "", err
  53. }
  54. roundedTime := t.Truncate(time.Minute) // 将时间截断到分钟级别
  55. roundedTimeString := roundedTime.Format("2006-01-02 15:04:00")
  56. return roundedTimeString, nil
  57. }