gpt4 book ai didi

java - 使用 before 方法比较两个日期(字符串格式的日期和当前时间)

转载 作者:行者123 更新时间:2023-12-02 05:07:21 24 4
gpt4 key购买 nike

我需要在Java中使用before方法。所以我可以像这样执行日期比较代码:

if (storedDate.before(currentMonth)) {

}

其中currentMonth设置如下:

int thisMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
cal = Calendar.getInstance(); df = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
cal.set(Calendar.MONTH, thisMonth);
// Do I even need to convert like this to match what is stored in the DB below?

storedDate 循环遍历 SQLite 表,其中日期存储为格式化字符串,例如“Nov 2013”​​或“Dec 2014”;是的,我知道设计很糟糕。

我需要做的是查看循环中当前行的日期是否早于本月;如果是这样,我会将其从 SQLite DB 中删除(我有该代码,这很好)。

那么,如何构建两个可以像这样进行比较的变量 if (storedDate.before(currentMonth)) {

编辑:

这就是月份存储到数据库中的方式:

            monthTotal = monthTotal + 1;

Calendar myDate = Calendar.getInstance();
myDate.add(Calendar.MONTH, monthTotal);

SimpleDateFormat dfEng = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
String finalDBDate = dfEng.format(myDate.getTime());

编辑2:

这是我到目前为止所拥有的

private void deleteOldSpecialPayments() {

int thisMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
cal = Calendar.getInstance();
df = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
cal.set(Calendar.MONTH, thisMonth);

String thisMonthS = df.format(cal.getTime());
Date currentDate = null;
try {
currentDate = df.parse(thisMonthS);
} catch (ParseException e) {
e.printStackTrace();
}

if (!database.isOpen()) {
open();
}

Cursor cursor = database.query(MySQLiteHelper.TABLE_CUSTOM_PAYMENTS, allLedgerColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
SpecialPayment sp = cursorToCustomPayments(cursor);
try {
Date d = df.parse(sp.month);
if (d.before(currentDate)) {
// DELETE ROW
}
} catch (ParseException e) {
e.printStackTrace();
}

cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
}

最佳答案

尚不完全清楚您要比较的值。很容易看出“现在”是否晚于特定月份的第一天开始:

// TODO: For testing purposes, you'd want a Clock abstraction to be injected.
Date now = new Date();
DateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);

// Each row...
for (...) {
Date storedDate = format.parse(textFromDatabase);
if (now.compareTo(storedDate) >= 0) {
// It is now on or after the start of the given month
}
}

但是,您可能不希望将月初存储在数据库中 - 您可能想要下个月的开始。例如,如果存储的月份是“2015 年 7 月”,那么您可能希望在用户所在时区的 7 月初删除该行,或者您可能希望等到 8 月初。对于八月初,您可以使用 java.util.Calendar (或者理想情况下 Joda Time )向存储的日期添加一个月,或者您可以按照 Elliott 的建议分别解析月份和年份在评论中。

关于java - 使用 before 方法比较两个日期(字符串格式的日期和当前时间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27662895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com