0

我有这些代码可以在我的服务器中获取今天的日期

 DefaultTableModel dnow = MyDB.DataTable("SELECT date_format(now(),'%m-%d-%Y')");

以及用于日期格式的这些代码。

SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");

现在我怎样才能得到昨天的日期?我应该用一个减去它吗?

4

4 回答 4

1

不,建立一个Date(或者更好的是使用jodaDateTime对象)然后做你的算术。我会给你两个解决方案,一个有 Joda,另一个没有,从没有开始:

Date d = format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()));
d.add(Calendar.DATE, -1);

现在,使用 joda:

DateTime d = new DateTime(format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()))).minusDays(1);
于 2013-04-25T02:43:01.783 回答
1

另一种方法是在 SQL 中进行数学运算。该语句可能会因您使用的数据库平台而异。

DefaultTableModel dnow = 
  MyDB.DataTable("SELECT date_format(now() - INTERVAL 1 DAY,'%m-%d-%Y')");
于 2013-04-25T03:29:04.400 回答
0

这对你来说应该是完美的,

Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date = "+ cal.getTime());

这只会从当前日历日期中减去 1 天,为您提供昨天的日期

于 2013-04-25T02:39:46.850 回答
0

如果您将时间戳在内部存储为 POSIX 时间(自 1970 年 1 月 1 日 MN 以来的毫秒数),那么您可以轻松地为任何时间戳添加或减去一天:

Date today = new Date(); // today
Date tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000)); // tomorrow

POSIX 时间的巨大好处是它始终采用 UTC。UTC 是一个全球性的“固定”参考点。然后,如果您需要在任何时区、任何夏令时区、奥尔森时区数据库中的任何地点为用户显示此日期,您可以简单地创建一个日历:

GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setCalendar(gc);
sdf.applyPattern("MM-dd-yyyy");

// Now your formatter is set with the pattern and a time zone-aware Calendar. 
// The world is at your command

String myOutput = sdf.format(tomorrow);

我强烈建议在您的数据模型中以某种 UTC 表示形式在内部处理时间戳。使用 POSIX 时间(或儒略日数,或修改后的儒略日数)进行日期运算很容易,Java 日期/时间 API 有足够的能力来处理大多数本地时间转换,而无需您大惊小怪。

于 2013-04-25T04:16:33.167 回答