继续从堆栈溢出问题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而不是解决方案。


当前回答

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

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

其他回答

以下是我过去把时间设置为00:00:00的今天日期:

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

Date today = new Date();

Date todayWithZeroTime = formatter.parse(formatter.format(today));

我们可以使用SimpleDateFormat将日期格式化为我们喜欢的格式。下面是一个工作示例:-

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(new Date())); //data can be inserted in this format function

输出:

15/06/2021

尽量不使用第三方库。我知道之前提到过这种方法,但这里有一种干净的方法:

  /*
    Return values:
    -1:    Date1 < Date2
     0:    Date1 == Date2
     1:    Date1 > Date2

    -2:    Error
*/
public int compareDates(Date date1, Date date2)
{
    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");

    try
    {
        date1 = sdf.parse(sdf.format(date1));
        date2 = sdf.parse(sdf.format(date2));
    }
    catch (ParseException e) {
        e.printStackTrace();
        return -2;
    }

    Calendar cal1 = new GregorianCalendar();
    Calendar cal2 = new GregorianCalendar();

    cal1.setTime(date1);
    cal2.setTime(date2);

    if(cal1.equals(cal2))
    {
        return 0;
    }
    else if(cal1.after(cal2))
    {
        return 1;
    }
    else if(cal1.before(cal2))
    {
        return -1;
    }

    return -2;
}

好吧,不使用gregoricalendar可能是一种选择!

我刚为我的应用程序做了这个:

public static Date getDatePart(Date dateTime) {
    TimeZone tz = TimeZone.getDefault();
    long rawOffset=tz.getRawOffset();
    long dst=(tz.inDaylightTime(dateTime)?tz.getDSTSavings():0);
    long dt=dateTime.getTime()+rawOffset+dst; // add offseet and dst to dateTime
    long modDt=dt % (60*60*24*1000) ;

    return new Date( dt
                    - modDt // substract the rest of the division by a day in milliseconds
                    - rawOffset // substract the time offset (Paris = GMT +1h for example)
                    - dst // If dayLight, substract hours (Paris = +1h in dayLight)
    );
}

Android API级别1,没有外部库。 它尊重日光和默认时区。没有字符串操作,所以我认为这种方式比你的CPU效率更高,但我没有做任何测试。

对于标准java运行时中的date例程,谈论没有时间戳的日期是没有意义的,因为它实际上映射到特定的毫秒而不是日期。所述毫秒本质上有一个时间附加到它,这使得它容易受到时区问题,如日光节约时间和其他日历调整。看看为什么这两次减去(1927年)会得到一个奇怪的结果?举个有趣的例子。

如果您希望使用日期而不是毫秒,则需要使用其他东西。对于Java 8,有一组新的方法可以提供您想要的东西。对于Java 7及更早版本,请使用http://www.joda.org/joda-time/