我有这些代码可以在我的服务器中获取今天的日期
DefaultTableModel dnow = MyDB.DataTable("SELECT date_format(now(),'%m-%d-%Y')");
以及这些日期格式的代码。
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
现在我怎样才能得到昨天的日期? 我应该用一个减去吗?
答案 0 :(得分:1)
不,构建Date
(或更好的使用joda的DateTime
对象),然后进行算术运算。我会给你两个解决方案,一个是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);
答案 1 :(得分:1)
另一种方法是在SQL中进行数学运算。声明可能因您使用的数据库平台而异。
DefaultTableModel dnow =
MyDB.DataTable("SELECT date_format(now() - INTERVAL 1 DAY,'%m-%d-%Y')");
答案 2 :(得分:0)
这应该对你有用,
Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date = "+ cal.getTime());
这将简单地从当前日历日期中减去1天,为您提供昨天的日期
答案 3 :(得分:0)
如果您在内部将时间戳存储为POSIX时间(自1970年1月1日以来的毫秒数),那么您可以像以下一样轻松地将一天添加或减去任何时间戳:
Date today = new Date(); // today
Date tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000)); // tomorrow
POSIX时间的巨大好处是它总是以UTC为单位。 UTC是一个全球性的“固定”参考点。然后,如果您需要在任何时区,任何夏令时区域中为用户显示此日期,对于在Olson时区数据库中计算的任何位置,您只需创建一个日历:
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时间(或Julian Day Numbers或Modified Julian Day Numbers)进行日期算术很容易,Java日期/时间API具有足够的能力来处理大多数本地时间转换,而不必大惊小怪。