Java程序获取当前日期/时间
要理解此示例,你应该具备以下 Java 编程主题的知识:
示例 1:以默认格式获取当前日期和时间
import java.time.LocalDateTime;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
System.out.println("当前日期和时间是: " + current);
}
}
输出
当前日期和时间是: 2017-08-02T11:25:44.973
在上述程序中,使用 LocalDateTime.now()
方法将当前日期和时间存储在变量 current
中。
对于默认格式,它使用 toString()
方法内部将 LocalDateTime
对象转换为字符串。
示例 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("当前日期和时间是: " + formatted);
}
}
输出
当前日期和时间是: 2017-08-02 11:29:57.401
在上述程序中,我们使用 DateTimeFormatter
对象定义了 年-月-日 小时:分钟:秒.毫秒
的格式模式。
然后,我们使用 LocalDateTime
的 format()
方法应用给定的 formatter
。这样我们就得到了格式化的字符串输出。
示例 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("当前日期是: " + formatted);
}
}
输出
当前日期是: 20170802
在上述程序中,我们使用了预定 义格式常量 BASIC_ISO_DATE
来获取当前的 ISO 日期作为输出。
示例 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("当前日期是: " + formatted);
}
}
输出
当前日期是: Aug 2, 2017 11:44:19 AM
在上述程序中,我们使用了本地化风格 Medium
来获取给定格式的当前日期时间。还有其他风格:Full
、Long
和 Short
。
如果你感兴趣,这里有所有 DateTimeFormatter 模式 的列表。