Go language to get the current time, time type conversion

Get the current time of the system

//获取系统当前日期
func GetDate()string{
   now := time.Now()//获取当前时间对象
   year := utils2.ToString(now.Year())
   month := now.Format("01")
   day := utils2.ToString(now.Format("02"))
   return year+"_"+month+"_"+day
}

convert time to timestamp

func Time2Timestamp (datetime string)int64{
	//时间 to 时间戳
	loc, err := time.LoadLocation("Asia/Shanghai")        //设置时区
	if err !=nil{
		loc = time.FixedZone("CST",8*3600)
	}
	rt := strings.Index("/", datetime)
	if rt ==-1{
		tt, _ := time.ParseInLocation("2006/01/02 15:04:05", datetime, loc) //2006-01-02 15:04:05是转换的格式如php的"Y-m-d H:i:s"
		return tt.Unix()*1000
	}
	tt, _ := time.ParseInLocation("2006-01-02 15:04:05", datetime, loc) //2006-01-02 15:04:05是转换的格式如php的"Y-m-d H:i:s"
	ret := tt.Unix()*1000
	return ret
}

Seconds timestamp converted to time

//秒时间戳转换为时间
func MToTime(ms string )(string ,error) {
   mInt,err :=strconv.ParseInt(ms,10,64)
   if err !=nil{
      return ms,err
   }
   tm :=time.Unix(mInt,0)
   return tm.Format("2006-01-02 03:04:05 PM"),nil
}

milliseconds timestamp to time

//毫秒时间戳转换为时间
func MsToTime(ms string )(string ,error) {
   msInt,err :=strconv.ParseInt(ms,10,64)
   if err !=nil{
      return ms,err
   }
   tm :=time.Unix(0,msInt*int64(time.Millisecond))
   return tm.Format("2006-01-02 03:04:05 PM"),nil
}

Guess you like

Origin blog.csdn.net/qq_48626761/article/details/125595654