在该程序中,您将学习以Java格式获取当前日期和时间。
示例1:以默认格式获取当前日期和时间
import java.time.LocalDateTime;
public class CurrentDateTime {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
System.out.println("当前日期和时间为: " + current);
}
}
运行该程序时,输出为:
当前日期和时间为: 2019-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对象定义了格式为Year-Month-Day Hours:Minutes:Seconds.Milliseconds的模式
然后,我们使用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。
Java程序获取当前工作目录 Java程序检查数组是否包含给定值
展开全部