我有一个字符串过期日期。但是我需要在过期日期的前一天执行一些SQL语句。我得到我的过期日期并通过以下方式获取:
I have a String expired date. But I need to perform some SQL statement the day before expired date falls. I get my expired date and by:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); String expiredDate = null; String currentDate = dateFormat.format(new Date()); Calendar cal = Calendar.getInstance(); try { cal.setTime(dateFormat.parse(loanDate)); cal.add(Calendar.WEEK_OF_YEAR, 2); expiredDate = dateFormat.format(cal.getTimeInMillis()); cal.add(Calendar.WEEK_OF_YEAR, -2); } catch (ParseException e) { e.printStackTrace(); }然后,我得到了一条if语句来执行SQL语句:
Then, I got an if statement to perform SQL statement:
if(expiredDate.equals(currentDate)){ promptExtensionDialog(); }我要实现的是if语句,而不是expiredDate本身,我需要在过期日期前一天到来,并与当前日期进行比较。我想知道如何实现这一目标?
What I am trying to achieve is for the if statement, instead of the expiredDate itself, I need to get one day before the expired date and compare with the current date. I wonder how to achieve this?
预先感谢。
编辑
try { cal.setTime(dateFormat.parse(expiredDate)); cal.add(Calendar.DATE, -1); expiredDate = dateFormat.format(cal.getTimeInMillis()); } catch (ParseException e) { e.printStackTrace(); } Toast.makeText(LoanBook.this, expiredDate, Toast.LENGTH_LONG) .show();这将返回下一个日期而不是上一个日期。您有任何想法吗?
This returns me the next date instead of previous date. Do you have any ideas?
推荐答案使用Java的内置(8之前的版本)Date and Time API可以使您活得死活。使用 JodaTime 进行复杂的DateTime操作。
Using Java's (pre-8) built-in Date and Time API will eat you alive. Use JodaTime for complex DateTime manipulations.
获取前一天就这么简单。
Getting the previous day is as simple as this.
DateTime dateTime = new DateTime(); System.out.println(dateTime); System.out.println(dateTime.minusDays(1));如果您不需要任何外部库:
If you don't want any external libraries:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String strDate = "2014-10-28"; Date date = sdf.parse(strDate); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DATE, -1); Date yesterday = calendar.getTime(); System.out.println(yesterday); System.out.println(date);更多推荐
Java在特定日期之前提前一天
发布评论