现在我正在使用此代码
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 的原因。 提前感谢您的帮助!
最佳答案
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 日这样的日期。
关于java - 如何检查日期对象是否等于昨天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3006150/