Skip to content

Instantly share code, notes, and snippets.

@chris-zh
Created October 9, 2016 06:08
Show Gist options
  • Save chris-zh/32a76dcf8f6ed175d298b5bde49462d6 to your computer and use it in GitHub Desktop.
Save chris-zh/32a76dcf8f6ed175d298b5bde49462d6 to your computer and use it in GitHub Desktop.
用LocalDateTime处理日期
public static void main(String[] args){
//获得当前日期 2016-10-09T13:15:16.386
LocalDateTime now = LocalDateTime.now();
System.out.println("now = " + now);
//获得3天后 2016-10-12T13:21:01.215
LocalDateTime threeDaysAfterNow = now.plusDays(3);
System.out.println("threeDaysAfterNow = " + threeDaysAfterNow);
//获得3天后的23:59:59 2016-10-12T13:16:42.377
LocalDateTime newTime = now.plusDays(3).withHour(23).withMinute(59).withSecond(59);
System.out.println("newTime = " + newTime);
//获得指定时间 2016-10-21T23:59:59
LocalDateTime specificTime = LocalDateTime.of(2016, 10, 21, 23, 59, 59);
System.out.println("specificTime = " + specificTime);
//解析日期字符串
LocalDateTime time1 = LocalDateTime.parse("2016-12-03T10:15:30.001");
System.out.println("time1 = " + time1);
LocalDateTime time2 = LocalDateTime.parse("2015-10-09T13:25:25");
//比较日期 result > 0 |= 0| < 0
int result = time1.compareTo(time2);
System.out.println("result = " + result);
//一个月后
LocalDateTime oneMonthAfter = now.plusMonths(1);
System.out.println("oneMonthAfter = " + oneMonthAfter);
//LocalDateTime转换成Timestamp类型 2016-12-03 10:15:30.001
Timestamp timestamp = Timestamp.valueOf(now);
System.out.println("timestamp = " + timestamp);
//LocalDateTime转换成字符串 2016-12-03T10:15:30.001
String nowString = now.toString();
System.out.println("nowString = " + nowString);
//LocalDateTime转换成Date Sun Oct 09 13:42:40 CST 2016
Date nowDate = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("nowDate = " + nowDate);
//Date转换成LocalDateTime 2016-10-09T14:07:48.651
LocalDateTime nowLocalDateTime = LocalDateTime.ofInstant(nowDate.toInstant(), ZoneId.systemDefault());
System.out.println("nowLocalDateTime = " + nowLocalDateTime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment