package lib import ( "crypto/md5" "encoding/hex" "github.com/shopspring/decimal" "math/rand" "strconv" "strings" "time" ) // #取得随机字符串:通过打乱slice来操作 func GetRandstring(length int, char string, rand_x int64) string { if length < 1 { return "" } if len(char) <= 6 || len(char) <= length { char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" } charArr := strings.Split(char, "") ran := rand.New(rand.NewSource(time.Now().Unix() + rand_x)) l := len(charArr) for i := l - 1; i > 0; i-- { r := ran.Intn(i) charArr[r], charArr[i] = charArr[i], charArr[r] } rchar := charArr[:length] return strings.Join(rchar, "") } // 返回一个32位md5加密后的字符串 func Md5(str string) string { h := md5.New() h.Write([]byte(str)) return hex.EncodeToString(h.Sum(nil)) } // 转化 func TimeStrToTime(T_time string) (time.Time, bool) { stamp, err := time.ParseInLocation("2006-01-02 15:04:05", T_time, time.Local) // +8 if err != nil { return time.Time{}, false } return stamp, true } func DateStrToTime(T_date string) (time.Time, bool) { stamp, err := time.ParseInLocation("2006-01-02", T_date, time.Local) // +8 if err != nil { return time.Time{}, false } return stamp, true } func MonthStrToTime(T_month string) (time.Time, bool) { stamp, err := time.ParseInLocation("2006-01", T_month, time.Local) // +8 if err != nil { return time.Time{}, false } return stamp, true } func SplitStringIds(str string, prefix string) (r []string) { if len(str) == 0 { return r } Ids_str := strings.TrimRight(str, "|") Ids := strings.Split(Ids_str, "|") for _, v := range Ids { r = append(r, strings.TrimLeft(v, prefix)) } return r } func SplitStringToDotStr(str string, prefix string) (r string) { if len(str) == 0 { return r } Ids_str := strings.TrimRight(str, "|") Ids := strings.Split(Ids_str, "|") for _, v := range Ids { r += strings.TrimLeft(v, prefix) + "," } r = strings.TrimRight(r, ",") return r } func SplitStringToIntIds(str string, prefix string) (r []int) { if len(str) == 0 { return r } Ids_str := strings.TrimRight(str, "|") Ids := strings.Split(Ids_str, "|") for _, v := range Ids { id, _ := strconv.Atoi(strings.TrimLeft(v, prefix)) r = append(r, id) } return r } func IntIdsDistinct(Ids []int) (result []int) { distinctMap := make(map[int]int, len(Ids)) for _, Id := range Ids { if _, ok := distinctMap[Id]; !ok { distinctMap[Id] = 1 result = append(result, Id) } } return result } func SplitString(str string, cutset string) (r []string) { if len(str) == 0 { return r } list := strings.Split(strings.TrimRight(str, cutset), cutset) return list } // string转float64保留2位小数 func StringToFloat64TwoDecimal(str string) float64 { temp, _ := strconv.ParseFloat(str, 64) f, _ := decimal.NewFromFloat(temp).Round(2).Float64() return f }