java 日历只有期待,没有日历的时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16429788/
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
Calendar with date only expecting, without time of the calendar?
提问by Mr.Chowdary
I'm comparing two dates one is a general date and other is got from gregorian calendar.
when i tried to compare both dates it is giving result false,
Later i realized that it is due to time difference. So even both dates are same and times different i want it to return true or set date of the latter to default.ie,0
我正在比较两个日期,一个是一般日期,另一个来自公历。
当我尝试比较两个日期时,结果是错误的,
后来我意识到这是由于时差造成的。因此,即使两个日期相同且时间不同,我也希望它返回 true 或将后者的日期设置为 default.ie,0
Eg: Start Date : Wed May 08 00:00:00 CAT 2013
End Date : Wed May 08 00:40:30 CAT 2013
I tried calender API, set(year,month,day,hour,minute,second); but setting year,month and day i don't know. Please help me this regard to fix it.
我试过日历 API, set(year,month,day,hour,minute,second); 但是设置年月日我不知道。请帮我解决这方面的问题。
回答by sagar
You can use simple java code to get date without time as below. This method will set time part for any date to 00:00:00
您可以使用简单的 java 代码来获取没有时间的日期,如下所示。此方法将任何日期的时间部分设置为 00:00:00
private Date getDateWithOutTime(Date targetDate) {
Calendar newDate = Calendar.getInstance();
newDate.setLenient(false);
newDate.setTime(targetDate);
newDate.set(Calendar.HOUR_OF_DAY, 0);
newDate.set(Calendar.MINUTE,0);
newDate.set(Calendar.SECOND,0);
newDate.set(Calendar.MILLISECOND,0);
return newDate.getTime();
}
回答by Youans
try
尝试
Calendar cal = Calendar.getInstance();
cal.set(2014,Calendar.JUNE,29,0,0,0);
date = cal.getTime();
回答by Evgeniy Dorofeev
You can round millis to days and compare them, this will be faster than Calendar based version
您可以将毫秒舍入到天并进行比较,这将比基于日历的版本更快
long t1 = date1.getTime() / 86400000 * 86400000;
long t2 = date2.getTime() / 86400000 * 86400000;
return Long.compare(t1, t2);