1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309 |
- package utils
- import (
- "bufio"
- "crypto/cipher"
- "crypto/des"
- "crypto/md5"
- "crypto/sha1"
- "encoding/base64"
- "encoding/hex"
- "encoding/json"
- "errors"
- "fmt"
- "image"
- "image/png"
- "io"
- "math"
- "math/rand"
- "net"
- "net/http"
- "os"
- "os/exec"
- "path"
- "regexp"
- "strconv"
- "strings"
- "time"
- "github.com/shopspring/decimal"
- "gorm.io/gorm"
- )
- var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
- func GetRandString(size int) string {
- 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", "!", "@", "#", "$", "%", "^", "&", "*"}
- randomSb := ""
- digitSize := len(allLetterDigit)
- for i := 0; i < size; i++ {
- randomSb += allLetterDigit[rnd.Intn(digitSize)]
- }
- return randomSb
- }
- func GetRandStringNoSpecialChar(size int) string {
- 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"}
- randomSb := ""
- digitSize := len(allLetterDigit)
- for i := 0; i < size; i++ {
- randomSb += allLetterDigit[rnd.Intn(digitSize)]
- }
- return randomSb
- }
- func StringsToJSON(str string) string {
- rs := []rune(str)
- jsons := ""
- for _, r := range rs {
- rint := int(r)
- if rint < 128 {
- jsons += string(r)
- } else {
- jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
- }
- }
- return jsons
- }
- func ToString(v interface{}) string {
- data, _ := json.Marshal(v)
- return string(data)
- }
- func MD5(data string) string {
- m := md5.Sum([]byte(data))
- return hex.EncodeToString(m[:])
- }
- func GetRandDigit(n int) string {
- return fmt.Sprintf("%0"+strconv.Itoa(n)+"d", rnd.Intn(int(math.Pow10(n))))
- }
- func GetRandNumber(n int) int {
- return rnd.Intn(n)
- }
- func GetRandInt(min, max int) int {
- if min >= max || min == 0 || max == 0 {
- return max
- }
- return rand.Intn(max-min) + min
- }
- func GetToday(format string) string {
- today := time.Now().Format(format)
- return today
- }
- func GetTodayLastSecond() time.Duration {
- today := GetToday(FormatDate) + " 23:59:59"
- end, _ := time.ParseInLocation(FormatDateTime, today, time.Local)
- return time.Duration(end.Unix()-time.Now().Local().Unix()) * time.Second
- }
- func GetBrithDate(idcard string) string {
- l := len(idcard)
- var s string
- if l == 15 {
- s = "19" + idcard[6:8] + "-" + idcard[8:10] + "-" + idcard[10:12]
- return s
- }
- if l == 18 {
- s = idcard[6:10] + "-" + idcard[10:12] + "-" + idcard[12:14]
- return s
- }
- return GetToday(FormatDate)
- }
- func WhichSexByIdcard(idcard string) string {
- var sexs = [2]string{"女", "男"}
- length := len(idcard)
- if length == 18 {
- sex, _ := strconv.Atoi(string(idcard[16]))
- return sexs[sex%2]
- } else if length == 15 {
- sex, _ := strconv.Atoi(string(idcard[14]))
- return sexs[sex%2]
- }
- return "男"
- }
- func SubFloatToString(f float64, m int) string {
- n := strconv.FormatFloat(f, 'f', -1, 64)
- if n == "" {
- return ""
- }
- if m >= len(n) {
- return n
- }
- newn := strings.Split(n, ".")
- if m == 0 {
- return newn[0]
- }
- if len(newn) < 2 || m >= len(newn[1]) {
- return n
- }
- return newn[0] + "." + newn[1][:m]
- }
- func SubFloatToFloat(f float64, m int) float64 {
- newn := SubFloatToString(f, m)
- newf, _ := strconv.ParseFloat(newn, 64)
- return newf
- }
- func SubFloatToFloatStr(f float64, m int) string {
- newn := SubFloatToString(f, m)
- return newn
- }
- func GetYearDiffer(start_time, end_time string) int {
- t1, _ := time.ParseInLocation("2006-01-02", start_time, time.Local)
- t2, _ := time.ParseInLocation("2006-01-02", end_time, time.Local)
- age := t2.Year() - t1.Year()
- if t2.Month() < t1.Month() || (t2.Month() == t1.Month() && t2.Day() < t1.Day()) {
- age--
- }
- return age
- }
- func GetSecondDifferByTime(start_time, end_time time.Time) int64 {
- diff := end_time.Unix() - start_time.Unix()
- return diff
- }
- func FixFloat(f float64, m int) float64 {
- newn := SubFloatToString(f+0.00000001, m)
- newf, _ := strconv.ParseFloat(newn, 64)
- return newf
- }
- func StrListToString(strList []string) (str string) {
- if len(strList) > 0 {
- for k, v := range strList {
- if k == 0 {
- str = v
- } else {
- str = str + "," + v
- }
- }
- return
- }
- return ""
- }
- func ErrNoRow() string {
- return "<QuerySeter> no row found"
- }
- func IsErrNoRow(err error) bool {
- if err == nil {
- return false
- }
- return errors.Is(err, gorm.ErrRecordNotFound)
- }
- func ValidateEmailFormatat(email string) bool {
- reg := regexp.MustCompile(RegularEmail)
- return reg.MatchString(email)
- }
- func ValidateMobileFormatat(mobileNum string) bool {
- reg := regexp.MustCompile(RegularMobile)
- return reg.MatchString(mobileNum)
- }
- func FileIsExist(filePath string) bool {
- _, err := os.Stat(filePath)
- return err == nil || os.IsExist(err)
- }
- func GetImgExt(file string) (ext string, err error) {
- var headerByte []byte
- headerByte = make([]byte, 8)
- fd, err := os.Open(file)
- if err != nil {
- return "", err
- }
- defer fd.Close()
- _, err = fd.Read(headerByte)
- if err != nil {
- return "", err
- }
- xStr := fmt.Sprintf("%x", headerByte)
- switch {
- case xStr == "89504e470d0a1a0a":
- ext = ".png"
- case xStr == "0000010001002020":
- ext = ".ico"
- case xStr == "0000020001002020":
- ext = ".cur"
- case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
- ext = ".gif"
- case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
- ext = ".tga"
- case xStr[:8] == "464f524d":
- ext = ".iff"
- case xStr[:8] == "52494646":
- ext = ".ani"
- case xStr[:4] == "4d4d" || xStr[:4] == "4949":
- ext = ".tiff"
- case xStr[:4] == "424d":
- ext = ".bmp"
- case xStr[:4] == "ffd8":
- ext = ".jpg"
- case xStr[:2] == "0a":
- ext = ".pcx"
- default:
- ext = ""
- }
- return ext, nil
- }
- func SaveImage(path string, img image.Image) (err error) {
- imgfile, err := os.Create(path)
- defer imgfile.Close()
- err = png.Encode(imgfile, img)
- return err
- }
- func DownloadImage(imgUrl string) (filePath string, err error) {
- imgPath := "./static/imgs/"
- fileName := path.Base(imgUrl)
- res, err := http.Get(imgUrl)
- if err != nil {
- fmt.Println("A error occurred!")
- return
- }
- defer res.Body.Close()
- reader := bufio.NewReaderSize(res.Body, 32*1024)
- filePath = imgPath + fileName
- file, err := os.Create(filePath)
- if err != nil {
- return
- }
- writer := bufio.NewWriter(file)
- written, _ := io.Copy(writer, reader)
- fmt.Printf("Total length: %d \n", written)
- return
- }
- func SaveBase64ToFile(content, path string) error {
- data, err := base64.StdEncoding.DecodeString(content)
- if err != nil {
- return err
- }
- f, err := os.Create(path)
- defer f.Close()
- if err != nil {
- return err
- }
- f.Write(data)
- return nil
- }
- func SaveBase64ToFileBySeek(content, path string) (err error) {
- data, err := base64.StdEncoding.DecodeString(content)
- exist, err := PathExists(path)
- if err != nil {
- return
- }
- if !exist {
- f, err := os.Create(path)
- if err != nil {
- return err
- }
- n, _ := f.Seek(0, 2)
- _, err = f.WriteAt([]byte(data), n)
- defer f.Close()
- } else {
- f, err := os.OpenFile(path, os.O_WRONLY, 0644)
- if err != nil {
- return err
- }
- n, _ := f.Seek(0, 2)
- _, err = f.WriteAt([]byte(data), n)
- defer f.Close()
- }
- return nil
- }
- func PathExists(path string) (bool, error) {
- _, err := os.Stat(path)
- if err == nil {
- return true, nil
- }
- if os.IsNotExist(err) {
- return false, nil
- }
- return false, err
- }
- func StartIndex(page, pagesize int) int {
- if page > 1 {
- return (page - 1) * pagesize
- }
- return 0
- }
- func PageCount(count, pagesize int) int {
- if count%pagesize > 0 {
- return count/pagesize + 1
- } else {
- return count / pagesize
- }
- }
- func TrimHtml(src string) string {
- re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
- src = re.ReplaceAllStringFunc(src, strings.ToLower)
- re, _ = regexp.Compile("\\<img[\\S\\s]+?\\>")
- src = re.ReplaceAllString(src, "[图片]")
- re, _ = regexp.Compile("class[\\S\\s]+?>")
- src = re.ReplaceAllString(src, "")
- re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
- src = re.ReplaceAllString(src, "")
- return strings.TrimSpace(src)
- }
- func TimeToTimestamp() {
- fmt.Println(time.Unix(1556164246, 0).Format("2006-01-02 15:04:05"))
- }
- func ToUnicode(text string) string {
- textQuoted := strconv.QuoteToASCII(text)
- textUnquoted := textQuoted[1 : len(textQuoted)-1]
- return textUnquoted
- }
- func VersionToInt(version string) int {
- version = strings.Replace(version, ".", "", -1)
- n, _ := strconv.Atoi(version)
- return n
- }
- func IsCheckInList(list []int, s int) bool {
- for _, v := range list {
- if v == s {
- return true
- }
- }
- return false
- }
- func round(num float64) int {
- return int(num + math.Copysign(0.5, num))
- }
- func toFixed(num float64, precision int) float64 {
- output := math.Pow(10, float64(precision))
- return float64(round(num*output)) / output
- }
- func GetWilsonScore(p, n float64) float64 {
- if p == 0 && n == 0 {
- return 0
- }
- 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)
- }
- func ChangeWordsToNum(str string) (numStr string) {
- words := ([]rune)(str)
- num := 0
- n := 0
- for i := 0; i < len(words); i++ {
- word := string(words[i : i+1])
- switch word {
- case "万":
- if n == 0 {
- n = 1
- }
- n = n * 10000
- num = num*10000 + n
- n = 0
- case "千":
- if n == 0 {
- n = 1
- }
- n = n * 1000
- num += n
- n = 0
- case "百":
- if n == 0 {
- n = 1
- }
- n = n * 100
- num += n
- n = 0
- case "十":
- if n == 0 {
- n = 1
- }
- n = n * 10
- num += n
- n = 0
- case "一":
- n += 1
- case "二":
- n += 2
- case "三":
- n += 3
- case "四":
- n += 4
- case "五":
- n += 5
- case "六":
- n += 6
- case "七":
- n += 7
- case "八":
- n += 8
- case "九":
- n += 9
- case "零":
- default:
- if n > 0 {
- num += n
- n = 0
- }
- if num == 0 {
- numStr += word
- } else {
- numStr += strconv.Itoa(num) + word
- num = 0
- }
- }
- }
- if n > 0 {
- num += n
- n = 0
- }
- if num != 0 {
- numStr += strconv.Itoa(num)
- }
- return
- }
- func Sha1(data string) string {
- sha1 := sha1.New()
- sha1.Write([]byte(data))
- return hex.EncodeToString(sha1.Sum([]byte("")))
- }
- func GetVideoPlaySeconds(videoPath string) (playSeconds float64, err error) {
- cmd := `ffmpeg -i ` + videoPath + ` 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//`
- out, err := exec.Command("bash", "-c", cmd).Output()
- if err != nil {
- return
- }
- outTimes := string(out)
- fmt.Println("outTimes:", outTimes)
- if outTimes != "" {
- timeArr := strings.Split(outTimes, ":")
- h := timeArr[0]
- m := timeArr[1]
- s := timeArr[2]
- hInt, err := strconv.Atoi(h)
- if err != nil {
- return playSeconds, err
- }
- mInt, err := strconv.Atoi(m)
- if err != nil {
- return playSeconds, err
- }
- s = strings.Trim(s, " ")
- s = strings.Trim(s, "\n")
- sInt, err := strconv.ParseFloat(s, 64)
- if err != nil {
- return playSeconds, err
- }
- playSeconds = float64(hInt)*3600 + float64(mInt)*60 + float64(sInt)
- }
- return
- }
- func GetMaxTradeCode(tradeCode string) (maxTradeCode string, err error) {
- tradeCode = strings.Replace(tradeCode, "W", "", -1)
- tradeCode = strings.Trim(tradeCode, " ")
- tradeCodeInt, err := strconv.Atoi(tradeCode)
- if err != nil {
- return
- }
- tradeCodeInt = tradeCodeInt + 1
- maxTradeCode = fmt.Sprintf("W%06d", tradeCodeInt)
- return
- }
- func ConvertToFormatDay(excelDaysString string) string {
- baseDiffDay := 38719 //在网上工具计算的天数需要加2天,什么原因没弄清楚
- curDiffDay := excelDaysString
- b, _ := strconv.Atoi(curDiffDay)
- realDiffDay := b - baseDiffDay
- realDiffSecond := realDiffDay * 24 * 3600
- baseOriginSecond := 1136185445
- resultTime := time.Unix(int64(baseOriginSecond+realDiffSecond), 0).Format("2006-01-02")
- return resultTime
- }
- func CheckPwd(pwd string) bool {
- compile := `([0-9a-z]+){6,12}|(a-z0-9]+){6,12}`
- reg := regexp.MustCompile(compile)
- flag := reg.MatchString(pwd)
- return flag
- }
- func GetMonthStartAndEnd(myYear string, myMonth string) (startDate, endDate string) {
- if len(myMonth) == 1 {
- myMonth = "0" + myMonth
- }
- yInt, _ := strconv.Atoi(myYear)
- timeLayout := "2006-01-02 15:04:05"
- loc, _ := time.LoadLocation("Local")
- theTime, _ := time.ParseInLocation(timeLayout, myYear+"-"+myMonth+"-01 00:00:00", loc)
- newMonth := theTime.Month()
- t1 := time.Date(yInt, newMonth, 1, 0, 0, 0, 0, time.Local).Format("2006-01-02")
- t2 := time.Date(yInt, newMonth+1, 0, 0, 0, 0, 0, time.Local).Format("2006-01-02")
- return t1, t2
- }
- func TrimStr(str string) (str2 string) {
- return strings.Replace(str, " ", "", -1)
- }
- func StrTimeToTime(strTime string) time.Time {
- timeLayout := "2006-01-02 15:04:05" //转化所需模板
- loc, _ := time.LoadLocation("Local") //重要:获取时区
- resultTime, _ := time.ParseInLocation(timeLayout, strTime, loc)
- return resultTime
- }
- func GetOrmInReplace(num int) string {
- template := make([]string, num)
- for i := 0; i < num; i++ {
- template[i] = "?"
- }
- return strings.Join(template, ",")
- }
- func GetGormInReplace(num int) string {
- if num == 0 {
- return ""
- }
- return "?"
- }
- func RevSlice(slice []int) []int {
- for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
- slice[i], slice[j] = slice[j], slice[i]
- }
- return slice
- }
- func GetTimeSubDay(t1, t2 time.Time) int {
- var day int
- swap := false
- if t1.Unix() > t2.Unix() {
- t1, t2 = t2, t1
- swap = true
- }
- t1_ := t1.Add(time.Duration(t2.Sub(t1).Milliseconds()%86400000) * time.Millisecond)
- day = int(t2.Sub(t1).Hours() / 24)
- if t1_.Day() != t1.Day() {
- day += 1
- }
- if swap {
- day = -day
- }
- return day
- }
- func GetDaysBetween2Date(format, date1Str, date2Str string) (int, error) {
- date1, err := time.ParseInLocation(format, date1Str, time.Local)
- if err != nil {
- return 0, err
- }
- date2, err := time.ParseInLocation(format, date2Str, time.Local)
- if err != nil {
- return 0, err
- }
- return int(date1.Sub(date2).Hours() / 24), nil
- }
- type MapSorter []Item
- type Item struct {
- Key int
- Val float64
- }
- func NewMapSorter(m map[int]float64) MapSorter {
- ms := make(MapSorter, 0, len(m))
- for k, v := range m {
- ms = append(ms, Item{k, v})
- }
- return ms
- }
- func (ms MapSorter) Len() int {
- return len(ms)
- }
- func (ms MapSorter) Less(i, j int) bool {
- return ms[i].Val > ms[j].Val // 按值排序
- }
- func (ms MapSorter) Swap(i, j int) {
- ms[i], ms[j] = ms[j], ms[i]
- }
- func InArrayByInt(idIntList []int, searchId int) (has bool) {
- for _, id := range idIntList {
- if id == searchId {
- has = true
- return
- }
- }
- return
- }
- func InArrayByStr(idStrList []string, searchId string) (has bool) {
- for _, id := range idStrList {
- if id == searchId {
- has = true
- return
- }
- }
- return
- }
- func GetDateByDateType(dateType int, tmpStartDate, tmpEndDate string) (startDate, endDate string) {
- startDate = tmpStartDate
- endDate = tmpEndDate
- switch dateType {
- case 1:
- startDate = "2000-01-01"
- endDate = ""
- case 2:
- startDate = "2010-01-01"
- endDate = ""
- case 3:
- startDate = "2015-01-01"
- endDate = ""
- case 4:
- startDate = "2021-01-01"
- endDate = ""
- case 5:
- case 6:
- endDate = ""
- case 7:
- startDate = "2018-01-01"
- endDate = ""
- case 8:
- startDate = "2019-01-01"
- endDate = ""
- case 9:
- startDate = "2020-01-01"
- endDate = ""
- case 11:
- startDate = "2022-01-01"
- endDate = ""
- }
- {
- if strings.Count(startDate, "-") == 1 {
- startDate = startDate + "-01"
- }
- if strings.Count(endDate, "-") == 1 {
- endDate = endDate + "-01"
- }
- }
- return
- }
- func GetDateByDateType2(dateType int, currDate time.Time) (startDate time.Time) {
- switch dateType {
- case 1:
- startDate = currDate.AddDate(0, -3, 0)
- case 2:
- startDate = currDate.AddDate(0, -6, 0)
- case 3:
- startDate = currDate.AddDate(-1, 0, 0)
- case 4:
- startDate = currDate.AddDate(-2, 0, 0)
- case 5:
- startDate = currDate.AddDate(-3, 0, 0)
- case 6:
- startDate = currDate.AddDate(-5, 0, 0)
- case 7:
- startDate = currDate.AddDate(-10, 0, 0)
- }
- return
- }
- func GetCeilNewNum(num float64, baseLen int) (newNum float64) {
- if num >= 1 {
- tmpNum := int(math.Ceil(num)) // 向上取整
- str := strconv.Itoa(tmpNum)
- lenStr := len(str)
- if lenStr > baseLen {
- newNumStr := str[0:baseLen]
- newNumInt, _ := strconv.Atoi(newNumStr)
- newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
- if newNum < num {
- newNumInt += 1
- newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
- }
- } else {
- newNum = float64(tmpNum)
- }
- return
- } else if num > 0 {
- str := strconv.FormatFloat(num, 'f', -1, 64)
- str = removeDecimalPoint(str)
- lenStr := len(str)
- if lenStr > baseLen {
- newNumStr := str[0:baseLen]
- newNumInt, _ := strconv.Atoi(newNumStr)
- newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
- if newNum < num {
- newNumInt += 1
- newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
- }
- } else {
- newNum = num
- }
- } else if num > -1 {
- str := strconv.FormatFloat(num, 'f', -1, 64)
- str = removeDecimalPoint(str)
- lenStr := len(str)
- if lenStr > baseLen {
- newNumStr := str[0:baseLen]
- newNumInt, _ := strconv.Atoi(newNumStr)
- newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
- newNum = -newNum
- if newNum < num {
- newNumInt -= 1
- newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
- newNum = -newNum
- }
- } else {
- newNum = num
- }
- if newNum == -0 {
- newNum = 0
- }
- } else { // 小于等于-1
- tmpNumFloat := math.Abs(num)
- tmpNum := int(math.Floor(tmpNumFloat)) // 向上取整
- str := strconv.Itoa(tmpNum)
- lenStr := len(str)
- if lenStr > baseLen {
- newNumStr := str[0:baseLen]
- newNumInt, _ := strconv.Atoi(newNumStr)
- newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
- newNum = -newNum
- if newNum < num {
- newNumInt -= 1
- newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
- newNum = -newNum
- }
- } else {
- newNum = float64(-tmpNum)
- }
- }
- return
- }
- func GetFloorNewNum(num float64, baseLen int) (newNum float64) {
- if num >= 1 {
- tmpNum := int(math.Floor(num)) // 向上取整
- str := strconv.Itoa(tmpNum)
- lenStr := len(str)
- if lenStr > baseLen {
- newNumStr := str[0:baseLen]
- newNumInt, _ := strconv.Atoi(newNumStr)
- newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
- if newNum < num {
- newNumInt -= 1
- newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
- }
- } else {
- newNum = float64(tmpNum)
- }
- return
- } else if num > 0 {
- str := strconv.FormatFloat(num, 'f', -1, 64)
- str = removeDecimalPoint(str)
- lenStr := len(str)
- if lenStr > baseLen {
- newNumStr := str[0:baseLen]
- newNumInt, _ := strconv.Atoi(newNumStr)
- newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
- if newNum > num {
- newNumInt -= 1
- newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
- }
- } else {
- newNum = num
- }
- } else if num > -1 {
- str := strconv.FormatFloat(num, 'f', -1, 64)
- str = removeDecimalPoint(str)
- lenStr := len(str)
- if lenStr > baseLen {
- newNumStr := str[0:baseLen]
- newNumInt, _ := strconv.Atoi(newNumStr)
- newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
- newNum = -newNum
- if newNum > num {
- newNumInt += 1
- newNum, _ = decimal.NewFromInt(int64(newNumInt)).Div(decimal.NewFromFloat(math.Pow(10, float64(baseLen)))).Float64()
- newNum = -newNum
- }
- } else {
- newNum = num
- }
- if newNum == -0 {
- newNum = 0
- }
- } else { // 小于等于-1
- tmpNumFloat := math.Abs(num)
- tmpNum := int(math.Ceil(tmpNumFloat)) // 向上取整
- str := strconv.Itoa(tmpNum)
- lenStr := len(str)
- if lenStr > baseLen {
- newNumStr := str[0:baseLen]
- newNumInt, _ := strconv.Atoi(newNumStr)
- newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
- newNum = -newNum
- if newNum > num {
- newNumInt += 1
- newNum = float64(newNumInt) * math.Pow(10, float64(lenStr-baseLen))
- newNum = -newNum
- }
- } else {
- newNum = float64(-tmpNum)
- }
- }
- return
- }
- func removeDecimalPoint(str string) string {
- str = str[strings.Index(str, ".")+1:]
- return str
- }
- func GetLocalIP() (ip string, err error) {
- addrs, err := net.InterfaceAddrs()
- if err != nil {
- return
- }
- for _, addr := range addrs {
- ipAddr, ok := addr.(*net.IPNet)
- if !ok {
- continue
- }
- if ipAddr.IP.IsLoopback() {
- continue
- }
- if !ipAddr.IP.IsGlobalUnicast() {
- continue
- }
- return ipAddr.IP.String(), nil
- }
- return
- }
- func GetDateByDateTypeV2(dateType int, tmpStartDate, tmpEndDate string, startYear, yearMax int) (startDate, endDate string) {
- startDate = tmpStartDate
- endDate = tmpEndDate
- switch dateType {
- case 1:
- startDate = "2000-01-01"
- endDate = ""
- case 2:
- startDate = "2010-01-01"
- endDate = ""
- case 3:
- startDate = "2015-01-01"
- endDate = ""
- case 4:
- startDate = "2021-01-01"
- endDate = ""
- case 5:
- case 6:
- endDate = ""
- case 7:
- startDate = "2018-01-01"
- endDate = ""
- case 8:
- startDate = "2019-01-01"
- endDate = ""
- case 9:
- startDate = "2020-01-01"
- endDate = ""
- case 11:
- startDate = "2022-01-01"
- endDate = ""
- case DateTypeNYears:
- if startYear == 0 { //默认取最近5年
- startYear = 5
- }
- if yearMax == 0 {
- return
- }
- startYear = startYear - 1
- baseDate, _ := time.Parse(FormatDate, fmt.Sprintf("%d-01-01", yearMax))
- startDate = baseDate.AddDate(-startYear, 0, 0).Format(FormatDate)
- endDate = ""
- }
- {
- if strings.Count(startDate, "-") == 1 {
- startDate = startDate + "-01"
- }
- if strings.Count(endDate, "-") == 1 {
- endDate = endDate + "-01"
- }
- }
- return
- }
- func GetColorMap() map[int]string {
- colorMap := make(map[int]string)
- colors := []string{"#0000FF", "#FF0000", "#999999", "#000000", "#7CB5EC", "#90ED7D", "#F7A35C", "#8085E9",
- "#F15C80", "#E4D354", "#2B908F", "#F45B5B", "#91E8E1", "#FDA8C7", "#8A4294",
- "#578B5A", "#0033FF", "#849EC1", "#FFDF0C", "#005496", "#00F0FF", "#4D535B",
- "#4F4C34", "#804141", "#86BABD", "#8AA3FF", "#960000", "#A173DB", "#A39340",
- "#CE814A", "#D1D2E6", "#EAB7B7", "#FF2E7A", "#FF4AF8", "#FF785B", "#FF9696", "#FFA800", "#FFBC97", "#FFDFDF"}
- for k, v := range colors {
- colorMap[k] = v
- }
- return colorMap
- }
- func GetDaysDiff1900(date string) int {
- tStart, err := time.ParseInLocation(FormatDate, "1899-12-30", time.Local)
- if err != nil {
- return 0
- }
- tEnd, err := time.ParseInLocation(FormatDate, date, time.Local)
- if err != nil {
- return 0
- }
- duration := tEnd.Sub(tStart).Hours() / 24
- days := int(duration)
- return days
- }
- func ReplaceFormulaByTagMap(valTagMap map[string]int, formulaStr string) string {
- funMap := getFormulaMap()
- for k, v := range funMap {
- formulaStr = strings.Replace(formulaStr, k, v, -1)
- }
- replaceCount := 0
- for tag, val := range valTagMap {
- dvStr := fmt.Sprintf("%v", val)
- formulaStr = strings.Replace(formulaStr, tag, dvStr, -1)
- replaceCount++
- }
- for k, v := range funMap {
- formulaStr = strings.Replace(formulaStr, v, k, -1)
- }
- return formulaStr
- }
- func GetFrequencyEn(frequency string) (frequencyEn string) {
- switch frequency {
- case "日度":
- frequencyEn = "day"
- return
- case "周度":
- frequencyEn = "week"
- return
- case "旬度":
- frequencyEn = "ten days"
- return
- case "月度":
- frequencyEn = "month"
- return
- case "季度":
- frequencyEn = "quarter"
- return
- case "年度":
- frequencyEn = "year"
- return
- }
- return
- }
- func DateConvMysqlConvMongo(dateCon string) string {
- cond := ""
- switch dateCon {
- case "=":
- cond = "$eq"
- case "<":
- cond = "$lt"
- case "<=":
- cond = "$lte"
- case ">":
- cond = "$gt"
- case ">=":
- cond = "$gte"
- }
- return cond
- }
- func DesBase64Decrypt(crypted []byte, desKey string) []byte {
- result, _ := base64.StdEncoding.DecodeString(string(crypted))
- remain := len(result) % 8
- if remain > 0 {
- mod := 8 - remain
- for i := 0; i < mod; i++ {
- result = append(result, 0)
- }
- }
- origData, err := TripleDesDecrypt(result, []byte(desKey))
- if err != nil {
- panic(any(err))
- }
- return origData
- }
- func TripleDesDecrypt(crypted, key []byte) ([]byte, error) {
- block, err := des.NewTripleDESCipher(key)
- if err != nil {
- return nil, err
- }
- blockMode := cipher.NewCBCDecrypter(block, key[:8])
- origData := make([]byte, len(crypted))
- blockMode.CryptBlocks(origData, crypted)
- origData = PKCS5UnPadding(origData)
- return origData, nil
- }
- func PKCS5UnPadding(origData []byte) []byte {
- length := len(origData)
- unpadding := int(origData[length-1])
- return origData[:(length - unpadding)]
- }
- func TimeTransferString(format string, t time.Time) string {
- str := t.Format(format)
- if t.IsZero() {
- return ""
- }
- return str
- }
- func HandleSystemAppointDateT(currDate time.Time, appointDay, frequency string) (date string, err error, errMsg string) {
- switch frequency {
- case "本周":
- day := int(currDate.Weekday())
- if day == 0 { // 周日
- day = 7
- }
- num := 0
- switch appointDay {
- case "周一":
- num = 1
- case "周二":
- num = 2
- case "周三":
- num = 3
- case "周四":
- num = 4
- case "周五":
- num = 5
- case "周六":
- num = 6
- case "周日":
- num = 7
- }
- day = num - day
- date = currDate.AddDate(0, 0, day).Format(FormatDate)
- case "本旬":
- day := currDate.Day()
- var tmpDate time.Time
- switch appointDay {
- case "第一天":
- if day <= 10 {
- tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
- } else if day <= 20 {
- tmpDate = time.Date(currDate.Year(), currDate.Month(), 11, 0, 0, 0, 0, currDate.Location())
- } else {
- tmpDate = time.Date(currDate.Year(), currDate.Month(), 21, 0, 0, 0, 0, currDate.Location())
- }
- case "最后一天":
- if day <= 10 {
- tmpDate = time.Date(currDate.Year(), currDate.Month(), 10, 0, 0, 0, 0, currDate.Location())
- } else if day <= 20 {
- tmpDate = time.Date(currDate.Year(), currDate.Month(), 20, 0, 0, 0, 0, currDate.Location())
- } else {
- tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
- }
- }
- date = tmpDate.Format(FormatDate)
- case "本月":
- var tmpDate time.Time
- switch appointDay {
- case "第一天":
- tmpDate = time.Date(currDate.Year(), currDate.Month(), 1, 0, 0, 0, 0, currDate.Location())
- case "最后一天":
- tmpDate = time.Date(currDate.Year(), currDate.Month()+1, 1, 0, 0, 0, 0, currDate.Location()).AddDate(0, 0, -1)
- }
- date = tmpDate.Format(FormatDate)
- case "本季":
- month := currDate.Month()
- var tmpDate time.Time
- switch appointDay {
- case "第一天":
- if month <= 3 {
- tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
- } else if month <= 6 {
- tmpDate = time.Date(currDate.Year(), 4, 1, 0, 0, 0, 0, currDate.Location())
- } else if month <= 9 {
- tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
- } else {
- tmpDate = time.Date(currDate.Year(), 10, 1, 0, 0, 0, 0, currDate.Location())
- }
- case "最后一天":
- if month <= 3 {
- tmpDate = time.Date(currDate.Year(), 3, 31, 0, 0, 0, 0, currDate.Location())
- } else if month <= 6 {
- tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
- } else if month <= 9 {
- tmpDate = time.Date(currDate.Year(), 9, 30, 0, 0, 0, 0, currDate.Location())
- } else {
- tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
- }
- }
- date = tmpDate.Format(FormatDate)
- case "本半年":
- month := currDate.Month()
- var tmpDate time.Time
- switch appointDay {
- case "第一天":
- if month <= 6 {
- tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
- } else {
- tmpDate = time.Date(currDate.Year(), 7, 1, 0, 0, 0, 0, currDate.Location())
- }
- case "最后一天":
- if month <= 6 {
- tmpDate = time.Date(currDate.Year(), 6, 30, 0, 0, 0, 0, currDate.Location())
- } else {
- tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
- }
- }
- date = tmpDate.Format(FormatDate)
- case "本年":
- var tmpDate time.Time
- switch appointDay {
- case "第一天":
- tmpDate = time.Date(currDate.Year(), 1, 1, 0, 0, 0, 0, currDate.Location())
- case "最后一天":
- tmpDate = time.Date(currDate.Year(), 12, 31, 0, 0, 0, 0, currDate.Location())
- }
- date = tmpDate.Format(FormatDate)
- default:
- errMsg = "错误的日期频度:" + frequency
- err = errors.New(errMsg)
- return
- }
- return
- }
- func CompareFloatByOpStrings(op string, a, b float64) bool {
- switch op {
- case "=":
- return a == b
- case ">":
- return a > b
- case ">=":
- return a >= b
- case "<=":
- return a <= b
- case "<":
- return a < b
- }
- return false
- }
- func GormDateStrToDateTimeStr(originalString string) (formatStr string) {
- formatStr = originalString
- if !strings.Contains(originalString, "T") {
- return
- }
- t, err := time.Parse(FormatDateWallWithLoc, originalString)
- if err != nil {
- fmt.Println("Error parsing time:", err)
- return
- }
- formatStr = t.Format(FormatDateTime)
- return
- }
- func GormDateStrToDateStr(originalString string) (formatStr string) {
- formatStr = originalString
- if !strings.Contains(originalString, "T") {
- return
- }
- t, err := time.Parse(FormatDateWallWithLoc, originalString)
- if err != nil {
- fmt.Println("Error parsing time:", err)
- return
- }
- formatStr = t.Format(FormatDate)
- return
- }
- func RoundNumber(num string, decimalPlaces int, hasPercent bool) string {
- numDecimal, _ := decimal.NewFromString(num)
- if hasPercent {
- numDecimal = numDecimal.Mul(decimal.NewFromInt(100))
- }
- numFloat, _ := numDecimal.Round(int32(decimalPlaces)).Float64()
- numStr := strconv.FormatFloat(numFloat, 'f', decimalPlaces, 64)
- if hasPercent {
- numStr += "%"
- }
- return numStr
- }
|