Java 获取没有时间的当前日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22390344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current date without time
提问by MakoBuk
I need to solve following issue. I need to create date for comparison with other, but the date has to be without time due to comparing timemillis.
我需要解决以下问题。我需要创建日期以与其他日期进行比较,但由于比较 timemillis,该日期必须没有时间。
I have tried many ways, but still unsuccessfully.
我尝试了很多方法,但仍然没有成功。
I would imagine format like this:
我会想象这样的格式:
Date(2014-13-03 0:00:00).getTimeMillis();
Do anyone know how?
有谁知道怎么做?
采纳答案by Luiggi Mendoza
You could use a Calendar
to solve this:
您可以使用 aCalendar
来解决这个问题:
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date desiredDate = cal.getTime();
回答by DmitryKanunnikoff
long time = new SimpleDateFormat("yyyy-dd-MM").parse("2014-13-03 0:00:00").getTime();
回答by Shawn
The best thing is joda-time if you can use it.
如果你可以使用它,最好的方法是 joda-time。
Otherwise, use Calendar API. call Calendar.set() to set hour, minute, second and millisecond to zero then you have a Date of the starting of the date.
否则,请使用日历 API。调用 Calendar.set() 将小时、分钟、秒和毫秒设置为零,然后您就有了日期开始的日期。
But, won't new DateTime().withTimeAtStartOfDay()be a much easier expression?
但是,new DateTime().withTimeAtStartOfDay()不是更容易表达吗?
回答by Jenna Pederson
You can use the Calendar.clear(field) method to clear the time portion of the date.
您可以使用 Calendar.clear(field) 方法清除日期的时间部分。
Calendar rightNow = Calendar.getInstance();
rightNow.clear(Calendar.HOUR);
rightNow.clear(Calendar.MINUTE);
rightNow.clear(Calendar.SECOND);
rightNow.clear(Calendar.MILLISECOND);
Date today = rightNow.getTime();
回答by Reimeus
In Java 8 you could do
在 Java 8 中你可以做
LocalDate date = LocalDate.of(2014, Month.MARCH, 13);