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


当前回答

如果希望当前日期为字符串,请尝试以下操作:

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

or

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));

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

其他回答

    // 2015/09/27 15:07:53
    System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );

    // 15:07:53
    System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );

    // 09/28/2015
    System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));

    // 20150928_161823
    System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );

    // Mon Sep 28 16:24:28 CEST 2015
    System.out.println( Calendar.getInstance().getTime() );

    // Mon Sep 28 16:24:51 CEST 2015
    System.out.println( new Date(System.currentTimeMillis()) );

    // Mon Sep 28
    System.out.println( new Date().toString().substring(0, 10) );

    // 2015-09-28
    System.out.println( new java.sql.Date(System.currentTimeMillis()) );

    // 14:32:26
    Date d = new Date();
    System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );

    // 2015-09-28 17:12:35.584
    System.out.println( new Timestamp(System.currentTimeMillis()) );

    // Java 8

    // 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
    System.out.println( ZonedDateTime.now() );

    // Mon, 28 Sep 2015 16:16:23 +0200
    System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) );

    // 2015-09-28
    System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class

    // 16
    System.out.println( LocalTime.now().getHour() );

    // 2015-09-28T16:16:23.315
    System.out.println( LocalDateTime.now() );

在Java 8中,它是:

LocalDateTime.now()

如果您需要时区信息:

ZonedDateTime.now()

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

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

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

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

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

我会继续回答这个问题,因为当我有同样的问题时,这就是我所需要的:

Date currentDate = new Date(System.currentTimeMillis());

currentDate现在是Java date对象中的当前日期。