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


当前回答

使用java 8的当前日期:首先,让我们使用java.time.LocalDate获取当前系统日期:

LocalDate localDate = LocalDate.now();

要获取任何其他时区的日期,我们可以使用LocalDate.now(ZoneId):

LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));

我们还可以使用java.time.LocalDateTime获取LocalDate的实例:

LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();

其他回答

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

在Java 8中,它是:

LocalDateTime.now()

如果您需要时区信息:

ZonedDateTime.now()

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

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

有许多不同的方法:

System.currentTimeMillis()日期日历

首先了解java.util.Date类

1.1如何获取当前日期

import java.util.Date;

class Demostration{
    public static void main(String[]args){
        Date date = new Date(); // date object
        System.out.println(date); // Try to print the date object
    }
}

1.2如何使用getTime()方法

import java.util.Date;
public class Main {
    public static void main(String[]args){
        Date date = new Date();
        long timeInMilliSeconds = date.getTime();
        System.out.println(timeInMilliSeconds);
    }
}

这将返回自1970年1月1日00:00:00 GMT以来的毫秒数,用于时间比较。

1.3如何使用SimpleDateFormat类设置时间格式

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

class Demostration{
    public static void main(String[]args){
        Date date=new Date();
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate=dateFormat.format(date);
        System.out.println(formattedDate);
    }
}

也可以尝试使用不同的格式模式,如“yyyy-MM-dd hh:MM:ss”,并选择所需的模式。http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

了解java.util.Calendar类

2.1使用日历类获取当前时间戳

import java.util.Calendar;

class Demostration{
    public static void main(String[]args){
        Calendar calendar=Calendar.getInstance();
        System.out.println(calendar.getTime());
    }
}

2.2尝试使用setTime和其他设置方法将日历设置为不同的日期。

资料来源:http://javau91.blogspot.com/

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

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

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