菜鸟问题:怎么判断两个Date型变量是同一天?

vuen 2002-12-28 11:04:49
如题,由于本菜鸟对Java不熟,现在想到最好办法就是把年,月,日取出分别判断,请问有没有更简单的办法?只要根据一个函数就能判断出来最好。
...全文
1482 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wang_zheng_wz 2002-12-29
  • 打赏
  • 举报
回复
java.util.Date的取年月日方法被deprecated了,但却replaced by java.util.Calendar的啊,看看api documentation,java中有api为什么不用,而去找麻烦,“简单是可靠性的前提”---dijkstra
xiao_yuer 2002-12-29
  • 打赏
  • 举报
回复
public int compareTo(Date anotherDate)是不行的,因为Date对象是精确到毫秒的,所以是同一天的两个Date对象并不一定会相等。
分别取出年月日来判断也不好,因为那些方法都已经被弃用了。
可以考虑先转化成字符串再进行比较:
boolean isSameDay(Date date1,Date date2) {
String DATE_FORMAT = "yyyy-MM-dd";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
date1Str = sdf.format(date1);
date2Str = sdf.format(date2);
return date1Str.equals(date2Str);
}
jinannanhai79 2002-12-28
  • 打赏
  • 举报
回复
public int compareTo(Date anotherDate)

Compares two Dates for ordering.Parameters:anotherDate - the Date to be compared.Returns:the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument
wang_zheng_wz 2002-12-28
  • 打赏
  • 举报
回复
没发现一个method就行的,分别取出年月日也不麻烦啊,才三个method
helpall 2002-12-28
  • 打赏
  • 举报
回复
Date d1,d2;
if(d1.compareTo(d2) == 0)
...

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧