时间戳、日期、秒转换

/**
 * 秒转换为时间戳
 */
Instant instant = Instant.ofEpochSecond(156);
Console.log(instant);
//通过系统默认时区创建ZonedDateTime
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault()); //2017-10-07T01:10:00.001+08:00[Asia/Shanghai]
//从ZonedDateTime中获取LocalDateTime部分
LocalDateTime dateTime = zonedDateTime.toLocalDateTime(); //2017-10-07T01:10:00.001
//格式化LocalDateTime
String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Console.log(time);

long timeStamp1 = instant.getLong(ChronoField.INSTANT_SECONDS);	//10位时间戳,按秒
long timeStamp2 = (Timestamp.valueOf(time)).getTime();		//13位时间戳,按毫秒
System.out.println("时间戳1:"+timeStamp1);
System.out.println("时间戳2:"+timeStamp2);
Console.log(DateUtil.formatBetween(timeStampToSeconds(timeStamp1*1000), BetweenFormatter.Level.SECOND));
Console.log(DateUtil.formatBetween(timeStamp2, BetweenFormatter.Level.MILLISECOND));
Console.log(TimeUnit.MILLISECONDS.toSeconds(timeStamp2));
/**
 * 日期转换成时间戳
 */
Console.log(Timestamp.valueOf("2023-06-03 10:11:28").getTime());
Console.log(DateUtil.parseDateTime("2023-06-03 10:11:28").getTime());
/**
 * 时间戳转换为秒
 * @param timeStamp
 * @return
 */
public static long timeStampToSeconds(long timeStamp){
	if(ObjectUtils.isEmpty(timeStamp) || timeStamp==0){
		return 0;
	}
	return TimeUnit.SECONDS.toSeconds(timeStamp);
}

/**
 * 时间戳转换成String日期
 * @param stamp
 * @return
 */
public static String stampToTime(long stamp) {
	if(ObjectUtils.isEmpty(stamp) || stamp==0){
		return null;
	}
	SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_PATTERN);
	long time = new Long(stamp)*1000L;
	return sdf.format(new Date(time));
}

你可能感兴趣的:(java,java,后端)