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


当前回答

 System.out.println( new SimpleDateFormat("yyyy:MM:dd - hh:mm:ss a").format(Calendar.getInstance().getTime()) );
    //2018:02:10 - 05:04:20 PM

AM/PM日期/时间

其他回答

看看Date课程。还有一个更新的Calendar类,它是执行许多日期/时间操作的首选方法(许多date方法已被弃用)

如果您只想要当前日期,那么创建一个新的date对象或调用Calendar.getInstance();。

只需尝试以下代码:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {
    public static void getCurrentTimeUsingDate() {
        Date date = new Date();
        String strDateFormat = "hh:mm:ss a";
        DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
        String formattedDate= dateFormat.format(date);
        System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
    }
    public static void getCurrentTimeUsingCalendar() {
        Calendar cal = Calendar.getInstance();
        Date date=cal.getTime();
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        String formattedDate=dateFormat.format(date);
        System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
    }
}

其样本输出为:

使用日期-12小时格式的当前时间:11:13:01 PM使用日历的当前时间-24小时格式:23:13:01

更多信息:

在Java中获取当前日期时间

如前所述,基本的Date()可以根据需要获取当前时间。在我最近大量使用Java Date的经验中,内置类有很多奇怪之处(以及许多Date类方法的弃用)。我觉得有一个奇怪的地方是,月份是基于0指数的,从技术角度来看,这是合理的,但实际情况可能非常令人困惑。

如果你只关心当前的日期,那就足够了——然而,如果你打算用日期进行大量的操作/计算,那么使用第三方库可能会非常有益(因为很多Java开发人员对内置功能不满意,所以有很多这样的库)。

我支持Stephen C的建议,因为我发现Joda time对简化我的日期工作非常有用,它也有很好的文档记录,你可以在整个网站上找到许多有用的例子。我甚至最终编写了一个静态包装类(作为DateUtils),我使用它来合并和简化所有常见的日期操作。

在Java 8中,它是:

LocalDateTime.now()

如果您需要时区信息:

ZonedDateTime.now()

如果您想打印花式格式化字符串:

System.out.println(ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME))

对于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/