在Java 8之前,java.util.Date是非线程安全的;而Java 8 提供的LocalDate/LocalTime/LocalDateTime是不可变类且线程安全的
使用如下:
public static void main(String args[]){
//get current date
LocalDate localDate = LocalDate.now();
System.out.println("当前日期 : "+localDate);//当前日期 : 2018-10-21
//get current datetime
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("当前时间 : "+localDateTime);//当前时间 : 2018-10-21T15:03:21.870
//get current Month ; type Month
Month month = localDateTime.getMonth();//print OCTOBER
// Month month1 = localDate.getMonth();
//get current Month ; type int
int monthInt = month.getValue();//print 10
//get day of month
int day = localDateTime.getDayOfMonth();//print 21
//get day of year
int day1 = localDateTime.getDayOfYear();//294
//get seconds
int seconds = localDateTime.getSecond();//21
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//datetime to String format "yyyy-MM-dd HH:mm:ss"
String string = dateTimeFormatter.format(localDateTime);
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//date to String format "yyyy-MM-dd"
String string1 = dateTimeFormatter1.format(localDate);
System.out.println("datetime : "+string+" date : "+string1);//datetime : 2018-10-21 15:06:03 date : 2018-10-21
//String to Date
String tmp = "2018-09-21";
String tmp1 = "2018-10-01 16:34:23";
LocalDate localDate1 = LocalDate.parse(tmp,dateTimeFormatter1);
LocalDateTime localDateTime1 = LocalDateTime.parse(tmp1,dateTimeFormatter);
System.out.println("date : "+localDate1+" datetime : "+localDateTime1);
//get current zone
ZoneId zoneId = ZoneId.systemDefault();
System.out.println("Current Zone : "+zoneId);//Current Zone : Asia/Shanghai
LocalDateTime localDateTime2 = localDateTime.withDayOfMonth(10).withYear(2017);
System.out.println("localDateTime2 : "+localDateTime2);
LocalDate localDate2 = LocalDate.of(2008,Month.NOVEMBER,11);//2008-11-11
System.out.println("localDate2 : "+localDate2);
LocalTime localTime = LocalTime.of(19,28);//19小时28分钟
System.out.println("localTime : "+localTime);
}