premise:
- The time format in the database is dateTime
- LocalDateTime in the JAVA class corresponds to dateTime in the database
Tools:
Note: The default is milliseconds as the granularity. Seconds as the granularity need to be released.
/**
* @author luo qinfeng
*/
@Component
public class TimeUtils {
/**
* 格式化传入的时间戳(毫秒)
* @param timeStamp
* @return
*/
private String TimeStampToTime(String timeStamp){
String formats = "yyyy-MM-dd HH:mm:ss";
//粒度:毫秒
Long timestamp = Long.parseLong(timeStamp) ;
//粒度:秒
// Long timestamp = Long.parseLong(timeStamp) * 1000 ;
return new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
}
/**
* Stinrg -> LocalDateTime
* @param time
* @return
*/
private LocalDateTime StringTimeToLocalDateTime(String time){
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localTime = LocalDateTime.parse(time,df);
return localTime;
}
/**
* LocalDateTime -> String
* @param time
* @return
*/
private String LocalDateTimeTimeToString(LocalDateTime time){
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String stringTime = df.format(time);
return stringTime;
}
/**
* 格式化返回给前端的时间 以毫秒为单位
* @param stringTime
* @return
*/
private Long StringTimeToTimeStamp(String stringTime) {
Long timestamp = null;
try {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(stringTime).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
//是毫秒
return timestamp;
}
/**
* 格式化localDateTime (2020-11-20T 19:30:56)
* @param timeFromDataBase
* @return 2020-11-20 19:30:56
*/
public String standerFormat(LocalDateTime timeFromDataBase){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String s_timeFromDataBase = formatter.format(timeFromDataBase);
String time = s_timeFromDataBase.replace("T", " ");
//毫秒
return time;
//秒
// return time/1000;
}
}