获取当前日期/时间的 Java 程序
要理解此示例,您应该具备以下 Java 编程的知识:
示例 1:以默认格式获取当前日期和时间
import java.time.LocalDateTime;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
System.out.println("Current Date and Time is: " + current);
}
}
输出
Current Date and Time is: 2017-08-02T11:25:44.973
在上面的程序中,使用 LocalDateTime.now()
获取当前日期和时间 bing 存储在变量 current
中。
示例 2:使用模式获取当前日期和时间
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String formatted = current.format(formatter);
System.out.println("Current Date and Time is: " + formatted);
}
}
输出
Current Date and Time is: 2017-08-02 11:29:57.401
在上面的程序中,我们使用 DateTimeFormatter
对象定义了一种格式模式 yyyy-MM-dd HH:mm:ss.SSS
。
然后,我们使用 LocalDateTime
的 format()
方法来使用给定的格式化程序. 这让当前的日期时间按照我们要求的格式输出。
示例 3:使用预定义常量获取当前日期时间
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
String formatted = current.format(formatter);
System.out.println("Current Date is: " + formatted);
}
}
输出
Current Date is: 20170802
在上面的程序中,我们使用了一个预定义的格式常量 BASIC_ISO_DATE
,将当前日期时间输出为 yyyymmdd
。
示例 4:以本地化样式获取当前日期时间
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
String formatted = current.format(formatter);
System.out.println("Current Date is: " + formatted);
}
}
输出
Current Date is: 2022年6月15日 上午10:01:33
在上面的程序中,我们使用本地化样式 Medium
以给定格式获取当前日期时间。还有其他样式: Full
, Long
和 Short
。
如果您有兴趣,这里是所有DateTimeFormatter 模式的列表。