【Java可复用工具类-评论时间】传入LocalDateTime参数,返回一个时间【过去、昨天、今天】。
作者:互联网
1、效果
2、代码
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Component
public class DateTimeResult {
public String getTime(LocalDateTime commentTime) {
//获取当天日期和时间
LocalDateTime nowTime = LocalDateTime.now();
//获取当天日期
LocalDate nowDate = LocalDate.now();
//获取当天0点时间
LocalDateTime zoneTime = LocalDateTime.of(nowDate,LocalTime.MIN);
//获取一个计算属性,计算评论时间和当前时间的间隔
Duration duration = Duration.between(commentTime,nowTime);
Duration duration1 = Duration.between(zoneTime,nowTime);
//计算评论距离现在时间的小时数
long hours = duration.toHours();
//计算当前时间距离今天0点的小时数
long zoneHour = duration1.toHours();
String s;
//判断评论时间是否处于今天或者昨天
if (hours<=24+zoneHour){
//判断是昨天还是今天
if(hours < zoneHour){
//今天,去掉日期,保留时间
s = "今天"+ LocalTime.from(commentTime);
}else{
//昨天
s = "昨天"+ LocalTime.from(commentTime);
}
}else{
//不在今天和昨天范围内,去掉时间,保留日期
LocalDate date = LocalDate.from(commentTime);
s= ""+date;
}
return s;
}
}
点击查看代码
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Component
public class DateTimeResult {
public String getTime(LocalDateTime commentTime) {
//获取当天日期和时间
LocalDateTime nowTime = LocalDateTime.now();
//获取当天日期
LocalDate nowDate = LocalDate.now();
//获取当天0点时间
LocalDateTime zoneTime = LocalDateTime.of(nowDate,LocalTime.MIN);
//获取一个计算属性,计算评论时间和当前时间的间隔
Duration duration = Duration.between(commentTime,nowTime);
Duration duration1 = Duration.between(zoneTime,nowTime);
//计算评论距离现在时间的小时数
long hours = duration.toHours();
//计算当前时间距离今天0点的小时数
long zoneHour = duration1.toHours();
String s;
//判断评论时间是否处于今天或者昨天
if (hours<=24+zoneHour){
//判断是昨天还是今天
if(hours < zoneHour){
//今天,去掉日期,保留时间
s = "今天"+ LocalTime.from(commentTime);
}else{
//昨天
s = "昨天"+ LocalTime.from(commentTime);
}
}else{
//不在今天和昨天范围内,去掉时间,保留日期
LocalDate date = LocalDate.from(commentTime);
s= ""+date;
}
return s;
}
}
标签:Java,java,time,复用,LocalDateTime,Duration,import,LocalDate 来源: https://www.cnblogs.com/lishilin-glut/p/16656571.html