Java处理日期、日历和时间的方式一直为社区所诟病,将 java.util.Date设定为可变类型,以及SimpleDateFormat的非线程安全使其应用非常受限。
Java 8 推出了全新的日期时间API,基于ISO标准日历系统,java.time包下的所有类都是不可变类型而且线程安全。
1、获取当前日期和时间
1.1 获取当前的日期,不包含时间
Java 8 中的 LocalDate 用于表示当天日期。和java.util.Date不同,它只有日期,不包含时间。当你仅需要表示日期时就用这个类。
import java.time.LocalDate;
publicclass Demo01 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("今天的日期:"+today);
}
}
/*
运行结果: 今天的日期:2018-02-05
*/
1.2 获取年、月、日信息
import java.time.LocalDate;
public class Demo02 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.println("year:"+year);
System.out.println("month:"+month);
System.out.println("day:"+day);
}
}
1.3 获取当前时间,不包含日期
当前时间就只包含时间信息,没有日期,比如:23:12:10
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println("获取当前的时间,不含有日期:"+time);
}
//获取当前的时间,不含有日期:09:52:34.091
1.4 获取当前的时间戳
通过Instant类获取,Instant类有一个静态工厂方法now()会返回当前的时间戳
import java.time.Instant;
publicclass Demo16 {
public static void main(String[] args) {
Instant timestamp = Instant.now();
System.out.println("What is value of this instant " + timestamp.toEpochMilli());
}
}
//What is value of this instant 1587866310342
2、时间格式化
2.1 使用预定义的格式化工具去解析或格式化日期
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
publicclass Demo17 {
public static void main(String[] args) {
String dayAfterTommorrow = "20180205";
LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(dayAfterTommorrow+" 格式化后的日期为: "+formatted);
}
}
//20180205 格式化后的日期为: 2018-02-05
2.2 字符串互转日期类型
LocalDateTime包含日期和时间,比如:2018-02-05 23:14:21
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
publicclass Demo18 {
public static void main(String[] args) {
//日期转字符串
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
String str = date.format(format1);
System.out.println("日期转换为字符串:"+str);
//日期转换为字符串:2020/04/26 10:02:36
// 字符串转日期
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDate date2 = LocalDate.parse(str,format2);
System.out.println("日期类型:"+date2);
// 日期类型:2020-04-26
}
}
3、时间加减计算
3.1 计算一周后的日期
和上个例子计算3小时以后的时间类似,这个例子会计算一周后的日期。LocalDate日期不包含时间信息,它的plus()方法用来增加天、周、月,ChronoUnit类声明了这些时间单位。由于LocalDate也是不变类型,返回后一定要用变量赋值。
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
publicclass Demo08 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("今天的日期为:"+today);
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("一周后的日期为:"+nextWeek);
//一周后的日期为:2020-05-03
}
}
3.2 计算一年前或一年后的日期
利用minus()方法计算一年前的日期
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
publicclass Demo09 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
System.out.println("一年前的日期 : " + previousYear);
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
System.out.println("一年后的日期:"+nextYear);
}
}
//一年前的日期 : 2019-04-26
//一年后的日期:2021-04-26
3.3 获取几小时后时间
通过增加小时、分、秒来计算将来的时间很常见。Java 8除了不变类型和线程安全的好处之外,还提供了更好的plusHours()方法替换add(),并且是兼容的。注意,这些方法返回一个全新的LocalTime实例,由于其不可变性,返回后一定要用变量赋值。
import java.time.LocalTime;
publicclass Demo07 {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(3);
System.out.println("三个小时后的时间为:"+newTime);
}
}
// 三个小时后的时间为:12:56:46.811
3.4 计算两个日期之间的天数和月数——Period
有一个常见日期操作是计算两个日期之间的天数、周数或月数。在Java 8中可以用java.time.Period类来做计算。下面这个例子中,我们计算了当天和将来某一天之间的月数。
import java.time.LocalDate;
import java.time.Period;
publicclass Demo15 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate java8Release = LocalDate.of(2018, 12, 14);
Period periodToNextJavaRelease = Period.between(today, java8Release);
System.out.println("Months left between today and Java 8 release : "
+ periodToNextJavaRelease.getMonths() );
}
}
//Months left between today and Java 8 release : -4
4、时间比较
4.1 判断两个日期是否相等
import java.time.LocalDate;
publicclass Demo04 {
public static void main(String[] args) {
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2018,2,5);
if(date1.equals(date2)){
System.out.println("时间相等");
}else{
System.out.println("时间不等");
}
}
}
4.2 判断日期是早于还是晚于另一个日期
如何判断给定的一个日期是大于某天还是小于某天?在Java 8中,LocalDate类有两类方法isBefore()和isAfter()用于比较日期。
调用isBefore()方法时,如果给定日期小于当前日期则返回true。
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
publicclass Demo11 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate tomorrow = LocalDate.of(2018,2,6);
if(tomorrow.isAfter(today)){
System.out.println("之后的日期:"+tomorrow);
}
LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
if(yesterday.isBefore(today)){
System.out.println("之前的日期:"+yesterday);
}
}
}
//之前的日期:2020-04-25
5、自定义特定日期
我们通过静态工厂方法now()非常容易地创建了当天日期,你还可以调用另一个有用的工厂方法LocalDate.of()创建任意日期, 该方法需要传入年、月、日做参数,返回对应的LocalDate实例。这个方法的好处是没再犯老API的设计错误,比如年度起始于1900,月份是从0开 始等等。
import java.time.LocalDate;
publicclass Demo03 {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2018,2,6);
System.out.println("自定义日期:"+date);
}
}
6、固定日期以及周期性时间
6.1 检查像生日这种周期性事件
import java.time.LocalDate;
import java.time.MonthDay;
publicclass Demo05 {
public static void main(String[] args) {
//从生出日期获取生日日期(只有月和日)
LocalDate date3 = LocalDate.of(2018,2,6);
MonthDay birthday = MonthDay.of(date3.getMonth(),date3.getDayOfMonth());
//获取当前时间日期(只有月和日)
LocalDate date1 = LocalDate.now();
MonthDay currentMonthDay = MonthDay.from(date1);
if(currentMonthDay.equals(birthday)){
System.out.println("是你的生日");
}else{
System.out.println("你的生日还没有到");
}
}
}
6.2 表示信用卡到期这类固定日期
import java.time.*;
publicclass Demo13 {
public static void main(String[] args) {
//获取当前年月以及当前月有多少天
YearMonth currentYearMonth = YearMonth.now();
System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
//构建当前年月
YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
//Days in month year 2020-04: 30
//Your credit card expires on 2019-02
}
}
6.3 检查闰年
import java.time.LocalDate;
publicclass Demo14 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
if(today.isLeapYear()){
System.out.println("This year is Leap year");
}else {
System.out.println("2018 is not a Leap year");
}
}
}
7、处理时区
Java 8不仅分离了日期和时间,也把时区分离出来了。现在有一系列单独的类如ZoneId来处理特定时区,ZoneDateTime类来表示某时区下的时间。这在Java 8以前都是 GregorianCalendar类来做的。
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
publicclass Demo12 {
public static void main(String[] args) {
// Date and time with timezone in Java 8
ZoneId america = ZoneId.of("America/New_York");
//通过时区构建LocalDateTime
LocalDateTime localtDateAndTime = LocalDateTime.now(america);
System.out.println("Current date and time in a particular timezone : " + localtDateAndTime );
//Current date and time in a particular timezone : 2020-04-25T23:35:20.647
//以时区格式显示时间
LocalDateTime ldt1 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
ZonedDateTime atZone = ldt1.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(atZone);
//2020-04-26T11:37:30.663+08:00[Asia/Shanghai]
}
}
8. Clock时钟类
Java 8增加了一个Clock时钟类用于获取当时的时间戳,或当前时区下的日期时间信息。以前用到System.currentTimeInMillis()和TimeZone.getDefault()的地方都可用Clock替换。
import java.time.Clock;
publicclass Demo10 {
public static void main(String[] args) {
// Returns the current time based on your system clock and set to UTC.
Clock clock = Clock.systemUTC();
System.out.println("Clock : " + clock.millis());
// Returns time based on system clock zone
Clock defaultClock = Clock.systemDefaultZone();
System.out.println("Clock : " + defaultClock.millis());
//Clock : 1587872434146
//Clock : 1587872434146
}
}







网友评论