继续从堆栈溢出问题Java程序,以获得当前日期没有时间戳:

获得Date对象而不包含时间的最有效方法是什么?除了这两种,还有别的办法吗?

// Method 1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateWithoutTime = sdf.parse(sdf.format(new Date()));

// Method 2
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
dateWithoutTime = cal.getTime();

更新:

我知道Joda-Time;我只是试图避免额外的库为这样一个简单的(我认为)任务。但根据目前的回答,Joda-Time似乎非常受欢迎,所以我可能会考虑一下。 通过高效,我的意思是我想避免像方法1所使用的那样创建临时对象字符串,同时方法2似乎是一种hack而不是解决方案。


当前回答

看看Veyder-time。它是一个简单而有效的java的替代品。util和joda时间。它有一个直观的API和只表示日期的类,没有时间戳。

其他回答

充分利用Java巨大的时区数据库的最直接的方法是正确的:

long currentTime = new Date().getTime();
long dateOnly = currentTime + TimeZone.getDefault().getOffset(currentTime);

这是一种简单的方法:

Calendar cal = Calendar.getInstance();
SimpleDateFormat dateOnly = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(dateOnly.format(cal.getTime()));

使用LocalDate.now()并转换为Date,如下所示:

Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());

你可以利用joda时间。

private Date dateWitoutTime(Date date){
 return new LocalDate(date).toDate()
}

你打电话说:

Date date = new Date();
System.out.println("Without Time = " + dateWitoutTime(date) + "/n  With time = " + date);

这个呢?

public static Date formatStrictDate(int year, int month, int dayOfMonth) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, dayOfMonth, 0, 0, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}