这是我参与更文挑战的第24天,活动详情查看: 更文挑战
前言
在没有LocalDate和LocalDateTime之前,Java的时间操作简直是一锅粥,有了之后,互相之间的转换又变成了一锅粥,本文将会总结一下这些时间如何进行相互之间的互换。
Java各种时间的初始化方法
//当前时间日期
Date date =new Date();
LocalDateTime ld =LocalDateTime.now();
//JodaDate当前时间日期
DateTime dateTime =DateTime.now();
//指定时间
LocalDateTime.of(2019,10,13,10,12);
//使用Date进行时间的初始化,既麻烦,还需要注意坑
Date date = new Date();
date.setYear(2018);
date.setMonth(0);
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
System.out.println("Date = " + date);
System.out.println("LocalDateTime = " + localDateTime);
//Date = Fri Jan 25 16:29:25 CST 3918
//LocalDateTime = 3918-01-25T16:29:25.752
//可以看到setYear都已经过时了,而且是在1900的基础上加
//setMonth更搞笑,0代表1月,1代表2月
//Joda指定时间
DateTime dt = new DateTime(2005, 3, 26, 12, 0, 0, 0);
复制代码
LocalDateTime和String互转
String变LocalDateTime
//1 - default time pattern
String time = "2019-03-27T10:15:30";
LocalDateTime localTimeObj = LocalDateTime.parse(time);
//2 - specific date time pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a");
String time1 = "2019-03-27 10:15:30 AM";
LocalDateTime localTimeObj1 = LocalDateTime.parse(time1, formatter);
复制代码
LocalDateTime变String
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a");
LocalDateTime now = LocalDateTime.now();
String dateTimeString = now.format(formatter);
复制代码
和前端做Json转换使用
这是jackson的注解
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime publishtime;
复制代码
Date和String互转
String变Date
String startTimeStr="2019-2-14 11:34";
String dateFormat="yyyy-MM-dd HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date startTime = sdf.parse(startTimeStr);
复制代码
返回的Json结果会有一些问题
所以最好还是返回一个对象,然后在对应的属性上添加时间格式的注解
这是jackson的注解
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date startTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private LocalDateTime endTime;
复制代码
fastjson的注解没有找到
下面的是spring框架自带的
org.springframework.format.annotation;
@DateTimeFormat(pattern =”yyyy-MM-dd HH:mm:ss”)
private LocalDateTime endTime;
需要注意的是,如果Json中输入的字符串是2019-11-1 00:00:00这种,仍然会报错,必须是01,这里需要注意一下。
Date变String
直接tostring,此时格式不好
Date test =new Date();
System.out.println(test.toString());
//输出的结果
//Fri Oct 25 15:20:58 CST 2019
按格式
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy/MM/dd HH:mm:ss”);
String date = sdf.format(new Date());
System.out.println(date);
可以用来去掉使用Date时的时分秒
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd”);
String dateStr = formatter.format(date);
goodsRecord.setCreateDate(formatter.parse(dateStr));
LocalDateTime和LocalDate互转
LocalDateTime变LocalDate
LocalDate date =LocalDateTime.of(2019,10,13,10,12).toLocalDate();
复制代码
LocalDate变LocalDateTime
LocalDateTime time =LocalDate.now().atStartOfDay();
LocalDateTime time2 =LocalDate.now().atTime(10,14);
复制代码
LocalDateTime和Date互转
LocalDateTime变Date
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
Date date = Date.from(localDate.atZone(ZoneId.systemDefault()).toInstant());
复制代码
Date变LocalDateTime
Date date = new Date();
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
System.out.println("Date = " + date);
System.out.println("LocalDateTime = " + localDateTime);
复制代码
JodaTime和Date互转
使用JodaTime
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.5</version>
</dependency>
复制代码
JodaTime变Date
Date date=startDate.toDate();
复制代码
String变JodaTime
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime startDate = DateTime.parse("2019-10-24 08:00:00",fmt);
复制代码
Date变JodaTime
Date date = new Date();
DateTime dateTime =new DateTime(date);
System.out.println("DateTime = " + dateTime);
//输出结果:DateTime = 2019-10-25T16:57:15.658+08:00
复制代码
开始结束时间操作
获取数据
当前端发送过来的是字符串2019-11-12 这种,而后端又想直接用Date接收为带时间的参数卡住结束那天的最后时间的时候
/**
* 开始时间
*/
private Date startTime;
/**
* 结束时间
*/
private Date endTime;
public Date getStartTime() {
return startTime;
}
public void setStartTime(String startTimeStr) {
if (StringUtils.isNotBlank(startTimeStr)) {
try {
startTimeStr = startTimeStr + " 00:00";
String dateFormat = "yyyy-MM-dd HH:mm";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
this.startTime = sdf.parse(startTimeStr);
} catch (Exception e) {
this.startTime = null;
}
} else {
this.startTime = null;
}
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(String endTimeStr) {
if (StringUtils.isNotBlank(endTimeStr)) {
try {
endTimeStr = endTimeStr + " 23:59:59";
String dateFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
this.endTime = sdf.parse(endTimeStr);
} catch (Exception e) {
this.endTime = null;
}
} else {
this.endTime = null;
}
}
复制代码
可以在对应的Set方法里面直接转换
遍历时间
当定时任务需要将对应的时间按月份拆开并进行遍历时
log.info("定时任务开始" + new Date());
// 所有数据开始时间
LocalDate date = LocalDate.of(2019, 6, 1);
ZonedDateTime zonedDateTime = date.atStartOfDay(ZoneId.systemDefault());
LocalDate today = LocalDate.now();
Period age = Period.between(date, today);
int years = age.getYears();
int months = age.getMonths();
int monthsNum = (years * 12) + months+1;
try {
for (int i = 0; i < monthsNum; i++) {
log.info(String.valueOf(i));
LocalDate startTimeOfMonth = date.plusMonths(i);
if (startTimeOfMonth.isAfter(today)) {
break;
} else {
LocalDateTime first = startTimeOfMonth.atStartOfDay();
LocalDateTime end = startTimeOfMonth.plusMonths(1).minusDays(1).atTime(23, 59, 59);
String firstDay = first.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
log.info(firstDay);
String lastDay = end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
log.info(lastDay);
}
}
} catch (Exception e) {
log.error("定时任务异常", e);
}
log.info("定时任务调用结束" + new Date());
复制代码
总结
本文介绍了LocalDate,LocalDateTime,Date,JodaTime,String之间进行转化的方法,方便用到的时候直接copy使用。