如何在Java8中获取今天的日期?
在Java8之前,要获取当前日期和时间,我们通常依赖于各种类,例如SimpleDateFormat,Calendar等。
示例
import java.text.DateFormat;import java.text.SimpleDateFormat;
import java.util.Date;
public class LocalDateJava8 {
public static void main(String args[]) {
Date date = new Date();
String timeFormatString = "hh:mm:ss a";
DateFormat timeFormat = new SimpleDateFormat(timeFormatString);
String currentTime = timeFormat.format(date);
System.out.println("Current time: "+currentTime);
String dateFormatString = "EEE, MMM d, ''yy";
DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
String currentDate = dateFormat.format(date);
System.out.println("Current date: "+currentDate);
}
}
输出结果
Current time: 05:48:34 PMCurrent date: Wed, Jul 24, '19
Java8中的日期和时间
从Java8开始,引入了java.time包。它提供了LocalDate,LocalTime,LocalDateTime,MonthDay等类。使用此包的类,您可以通过更简单的方式获取时间和日期。
Java.time.LocalDate-此类表示ISO- 8601日历系统中不带时区的日期对象。now()
此类的方法从系统时钟获取当前日期。
Java.time.LocalTime-此类表示ISO- 8601日历系统中没有时区的时间对象。now()
此类的方法从系统时钟获取当前时间。
Java.time.LocalDateTime-此类表示ISO- 8601日历系统中没有时区的日期时间对象。now()
此类的方法从系统时钟获取当前日期时间。
示例
以下示例使用Java8的java.time包检索当前日期,时间和日期时间值。
import java.time.LocalDate;import java.time.LocalDateTime;
import java.time.LocalTime;
public class LocalDateJava8 {
public static void main(String args[]) {
//获取当前日期值
LocalDate date = LocalDate.now();
System.out.println("Current date: "+date);
//获取当前时间值
LocalTime time = LocalTime.now();
System.out.println("Current time: "+time);
//获取当前日期时间值
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("Current date-time: "+dateTime);
}
}
输出结果
Current date: 2019-07-24Current time: 18:08:05.923
Current date-time: 2019-07-24T18:08:05.923
以上是 如何在Java8中获取今天的日期? 的全部内容, 来源链接: utcz.com/z/321788.html