LocalDat类
1,LocalDate类
LocalDate类使用ISO日历表示年、月、日。
(1)LocalDatenow():获取系统当前日期;
(2)LocalDate.of(int year, int month, int dayOfMonth) 按指定日期创建LocalDate对象
(3)getYear:返回日期中的年份
(4)getMonth:返回日期中的月份
(5)getDayOfMonth:返回月份中的日
import java.time.LocalDate;
public class LocalDateTest {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
System.out.println(date);
System.out.println(date.getYear());
System.out.println(date.getMonth());
System.out.println(date.getDayOfMonth());
}
}
2,LocalTime类
(1)LocalTime.now():获取系统当前时间
(2)LocalTime.of(int hour, int minute, int second)按指定时间创建LocalTime对象
(3)getHour():返回小时
(4)getMinute():返回分钟
(5)getSecond():返回秒
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println(time);
System.out.println(time.getHour() + "时");
System.out.println(time.getMinute() + "分");
System.out.println(time.getSecond() + "秒");
}
3,LocalDateTime类
常用方法:
(1)LocalDateTime.now():获取系统当前时间
(2)LocalDateTime.of(int year, int month, int dayOfMonth, int hour, int minute, int second)指定日期和时间创建LocalDateTime对象。
(3)getYear:返回日期中的年份
(4)getMonth:返回日期中的月份
(5)getDayOfMonth:返回月份中的日
(6)getHour():返回小时
(7)getMinute():返回分钟
(8)getSecond():返回秒
测试方法:
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.now();
System.out.println(date);
System.out.println(date.getYear());
System.out.println(date.getMonth());
System.out.println(date.getDayOfMonth());
System.out.println(date.getHour());
System.out.println(date.getMinute());
System.out.println(date.getSecond());
}
4,DateTimeFormatter类
该类用于解析日期对象
常用方法:
(1)ofPatter(String pattern):按pattern字符串指定的格式创建
(2)LcalDateTime.parse(strDate, formatter):
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime date = LocalDateTime.parse("2016-11-22 13:22:44", formatter);
System.out.println(date + ", class:" + date.getClass());
}
5,ZonedDateTime处理日期和时间与相应的时区
常用方法:
(1)ZonedDateTime.now():获取日期当前日期和时间,
(2)String format(DateTimeFormatter formatter) 将日期转换为一个字符串
测试方法:
public static void main(String[] args) {
ZonedDateTime date = ZonedDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy:HH:mm:ss");
String strDate = date.format(formatter);
System.out.println(strDate);
}