本文介绍了如何检查日期对象是否等于昨天?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在使用这个代码

Right now I am using this code

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE) - 1, 12, 0, 0); //Sets Calendar to "yeserday, 12am"
if(sdf.format(getDateFromLine(line)).equals(sdf.format(cal.getTime())))                         //getDateFromLine() returns a Date Object that is always at 12pm
{...CODE

必须有一种更流畅的方法来检查 getdateFromLine() 返回的日期是否是昨天的日期.重要的是日期,而不是时间.这就是我使用 SimpleDateFormat 的原因.提前感谢您的帮助!

There's got to be a smoother way to check if the date returned by getdateFromLine() is yesterday's date. Only the date matters, not the time. That's why I used SimpleDateFormat.Thanks for your help in advance!

推荐答案

Calendar c1 = Calendar.getInstance(); // today
c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday

Calendar c2 = Calendar.getInstance();
c2.setTime(getDateFromLine(line)); // your date

if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
  && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR)) {

这也适用于 1 月 1 日这样的日期.

This will also work for dates like 1st of January.

这篇关于如何检查日期对象是否等于昨天?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:32