在Java中获取当前日期/时间的最佳方法是什么?


当前回答

与上述解决方案类似。但我总是发现自己在寻找这段代码:

Date date=Calendar.getInstance().getTime();
System.out.println(date);

其他回答

创建日期对象并将其打印下来。

Date d = new Date(System.currentTimeMillis());
System.out.print(d);

你看过java.util.Date吗?这正是你想要的。

对于java.util.Date,只需创建一个新的Date()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43

对于java.util.Calendar,使用Calendar.getInstance()

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43

对于java.time.LocalDateTime,使用LocalDateTime.now()

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43

对于java.time.LocalDate,使用LocalDate.now()

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16

参考:https://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

与上述解决方案类似。但我总是发现自己在寻找这段代码:

Date date=Calendar.getInstance().getTime();
System.out.println(date);

Use:

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp );

(它起作用了。)