Go--工具类集合

声明

1)该文章整理自网上的大牛和专家无私奉献的资料,具体引用的资料请看参考文献。
2)本文仅供学术交流,非商用。如果某部分不小心侵犯了大家的利益,还望海涵,并联系博主删除。
3)博主才疏学浅,文中如有不当之处,请各位指出,共同进步,谢谢。
4)此属于第一版本,若有错误,还需继续修正与增删。还望大家多多指点。大家都共享一点点,一起为祖国科研的推进添砖加瓦。

代码

//时间格式转换
package date

import (
	"strconv"
	"time"
)

const (
	FmtDate              = "2006-01-02"
	FmtTime              = "15:04:05"
	FmtDateTime          = "2006-01-02 15:04:05"
	FmtDateTimeNoSeconds = "2006-01-02 15:04"
)

// 秒时间戳
func NowUnix() int64 {
	return time.Now().Unix()
}

// 秒时间戳转时间
func FromUnix(unix int64) time.Time {
	return time.Unix(unix, 0)
}

// 当前毫秒时间戳
func NowTimestamp() int64 {
	return Timestamp(time.Now())
}

// 毫秒时间戳
func Timestamp(t time.Time) int64 {
	return t.UnixNano() / 1e6
}

// 毫秒时间戳转时间
func FromTimestamp(timestamp int64) time.Time {
	return time.Unix(0, timestamp*int64(time.Millisecond))
}

// 时间格式化
func Format(time time.Time, layout string) string {
	return time.Format(layout)
}

// 字符串时间转时间类型
func Parse(timeStr, layout string) (time.Time, error) {
	return time.Parse(layout, timeStr)
}

// return yyyyMMdd
func GetDay(time time.Time) int {
	ret, _ := strconv.Atoi(time.Format("20060102"))
	return ret
}

// 返回指定时间当天的开始时间
func WithTimeAsStartOfDay(t time.Time) time.Time {
	return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}

/**
 * 将时间格式换成 xx秒前,xx分钟前...
 * 规则:
 * 59秒--->刚刚
 * 1-59分钟--->x分钟前(23分钟前)
 * 1-24小时--->x小时前(5小时前)
 * 昨天--->昨天 hh:mm(昨天 16:15)
 * 前天--->前天 hh:mm(前天 16:15)
 * 前天以后--->mm-dd(2月18日)
 */
func PrettyTime(milliseconds int64) string {
	t := FromTimestamp(milliseconds)
	duration := (NowTimestamp() - milliseconds) / 1000
	if duration < 60 {
		return "刚刚"
	} else if duration < 3600 {
		return strconv.FormatInt(duration/60, 10) + "分钟前"
	} else if duration < 86400 {
		return strconv.FormatInt(duration/3600, 10) + "小时前"
	} else if Timestamp(WithTimeAsStartOfDay(time.Now().Add(-time.Hour*24))) <= milliseconds {
		return "昨天 " + Format(t, FmtTime)
	} else if Timestamp(WithTimeAsStartOfDay(time.Now().Add(-time.Hour*24*2))) <= milliseconds {
		return "前天 " + Format(t, FmtTime)
	} else {
		return Format(t, FmtDate)
	}
}

//num转换
package number

import "strconv"

// ToInt64 str to int64,如果转换失败,默认值为0
// str 字符串
func ToInt64(str string) int64 {
	return ToInt64ByDefault(str, 0)
}

// ToInt64ByDefault str to int64
// str 字符串
// def 如果转换失败使用的默认值
func ToInt64ByDefault(str string, def int64) int64 {
	val, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		val = def
	}
	return val
}

// ToInt str to int,如果转换失败,默认值为0
// str 字符串
func ToInt(str string) int {
	return ToIntByDefault(str, 0)
}

// ToIntByDefault str to int
// str 字符串
// def 如果转换失败使用的默认值
func ToIntByDefault(str string, def int) int {
	val, err := strconv.Atoi(str)
	if err != nil {
		val = def
	}
	return val
}

package gutil
 
import (
	"crypto/rand"
	"fmt"
	"math/big"
	"strconv"
)
 
 
/*
	input: [1,2,3,4]
	output: ?,?,?,? [1 2 3 4]
*/
// GetSQLPlaceholder sql参数拼接
func GetSQLPlaceholder(list []string, params []interface{}) (s string, paramList []interface{}) {
	n := len(list)
	for i := 0; i < len(list); i++ {
		s += "?"
		if i < n-1 {
			s += ","
		}
		paramList = append(paramList, list[i])
	}
	return
}
 
 
/*
 input: [1,2,3,4]
 output: 1,2,3,4
*/
// GetInt64SliceToString int64数组转为string
func GetInt64SliceToString(list []int64) (s string) {
	n := len(list)
	for i := 0; i < len(list); i++ {
		s += fmt.Sprintf("%v", list[i])
		if i < n-1 {
			s += ","
		}
	}
	return
}
 
 
/*
	intput: 1,2
	output: 2
*/
// IntMax get max
func IntMax(i1, i2 int) int {
	if i1 > i2 {
		return i1
	}
	return i2
}
 
// GenRandCountForDiff 生成指定范围内的指定个数(不同的数字)
func GenRandCountForDiff(min, max int64, count int) []int64 {
	var (
		allCount map[int64]int64
		result   []int64
	)
	allCount = make(map[int64]int64)
	maxBigInt := big.NewInt(max)
	for {
		// rand
		i, _ := rand.Int(rand.Reader, maxBigInt)
		number := i.Int64()
		// 是否大于下标
		if i.Int64() >= min {
			// 是否已经存在
			_, ok := allCount[number]
			if !ok {
				result = append(result, number)
				// 添加到map
				allCount[number] = number
			}
		}
		if len(result) >= count {
			return result
		}
	}
}
 
// GenRandCountByArea 随机生成指定范围内的数
func GenPiecesCount(min, max int64) int32 {
	maxBigInt := big.NewInt(max)
	for {
		i, _ := rand.Int(rand.Reader, maxBigInt)
		if i.Int64() >= min {
			return int32(i.Int64())
		}
	}
}
 
// StringSiceToInt64 string数组转[]int64
func StringSiceToInt64(str []string) []int64 {
	var (
		ids []int64
	)
	for _, i := range str {
		id, err := strconv.ParseInt(i, 10, 64)
		if err != nil {
			continue
		}
		ids = append(ids, id)
	}
	return ids
}
 
// RemoveElementToint32 移除数组内的指定元素
func RemoveElementToint32(list []int32, value int32) []int32 {
	var result = make([]int32, 0)
	index := 0
	endIndex := len(list) - 1
	for i, s := range list {
		if s == value {
			result = append(result, list[index:i]...)
			index = i + 1
		} else if i == endIndex {
			result = append(result, list[index:endIndex+1]...)
		}
	}
	return result
}
 
 
// Int64ToString int64->string
func Int64ToString(n int64) string {
	return strconv.FormatInt(n, 10)
}
 
 
/*
	input: 12.3455
	output: 12
*/
// Float32ToInt64 float32转为int64
func Float32ToInt64(count float32) (int64, error) {
	countStr := fmt.Sprintf("%0.0f", count)
	return strconv.ParseInt(depositStr, 10, 64)
}
//时间判断
func main(){
	t := time.Now()
	loc, _ := time.LoadLocation("Local")
	timeLayout := "2006-01-02"
	time1 := v.Start
	time2 := v.End
	tmp1, _ := time.ParseInLocation(timeLayout, time1, loc)
	tmp2, _ := time.ParseInLocation(timeLayout, time2, loc)
	timestamp1 := tmp1.Unix()
	timestamp2 := tmp2.Unix()
	//判断当前时间在开始时间-结束时间之间
	if t.Unix() >= timestamp1 && t.Unix() < timestamp2 {
		Item.Statue = 1
	}
	//判断当前时间在开始时间-结束时间之前
	if t.Unix() < timestamp1 && t.Unix() < timestamp2 {
		Item.Statue = 2
	}
	//判断当前时间在开始时间-结束时间之后
	if t.Unix() > timestamp1 && t.Unix() > timestamp2 {
		Item.Statue = 3
	}
	
	//获取当前月
	mon := int(time.Now().Month())
	//判断是上半年还是下半年
	if (mon >= 1 && mon <= 6) ||  (mon >= 7 && mon <= 12) {
		isNeed = true
	}
}

// 获取预定时间和当前时间相差的秒数
func differTime(afterTime string) int {
	thNow := time.Now().Hour()   //当前小时
	tmNow := time.Now().Minute() //当前分钟

	t1Split := strings.Split(afterTime, ":")
	thAfter, _ := strconv.Atoi(t1Split[0]) //未来执行小时
	tmAfter, _ := strconv.Atoi(t1Split[1]) //未来执行分钟

	diff := (thAfter-thNow)*60*60 + (tmAfter-tmNow)*60
	// 由于发送有延迟,提前半小时
	diff = diff - 30*60
	if diff <= 0 {
		// 立即发送,不能 < 1
		diff = 1
	}
	logger.Infof("预计 %v 秒后执行发送任务", diff)
	return diff
}
		
// 周期性任务
func CrontabMail() {
	c := cron.New()
	// 每天凌晨两点执行
	spec := "0 0 2 * * ?"
	c.AddFunc(spec, func() {
		RestTimingMail()//定时执行的方法
	})
	c.Start()

	select {}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Hibernate Validator 是一个基于 JSR 380 规范实现的校验框架,它提供了一系列的注解和 API,方便我们对 Java 对象进行校验。下面给出一个 Hibernate Validator 校验工具类的示例: ```java public class ValidationUtils { private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); /** * 校验对象 * @param object 待校验对象 * @param groups 待校验的组 * @throws ValidationException 校验不通过,则报ValidationException异常 */ public static void validateEntity(Object object, Class<?>... groups) throws ValidationException { Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups); if (!constraintViolations.isEmpty()) { StringBuilder msg = new StringBuilder(); for (ConstraintViolation<Object> constraintViolation : constraintViolations) { msg.append(constraintViolation.getMessage()).append(";"); } throw new ValidationException(msg.toString()); } } } ``` 上述代码定义了一个名为 ValidationUtils 的工具类,其中包含了一个名为 validateEntity 的静态方法。该方法接收两个参数,其中 object 表示待校验的对象,groups 表示校验分组。方法内部使用 Hibernate Validator 的 API 进行校验,并将校验结果保存在 constraintViolations 集合中。如果集合不为空,则表示校验不通过,将所有错误消息拼接起来,并抛出 ValidationException 异常。如果集合为空,则表示校验通过,方法直接返回。 可以看出,使用 Hibernate Validator 编写校验工具类非常简单,只需要创建一个 Validator 对象并调用其 validate 方法即可。对于校验不通过的情况,可以将所有错误消息拼接起来,或者只取第一个错误消息作为异常消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值