有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java减去日期得到昨天的日期

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

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

这些代码用于日期的格式

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

现在我怎么才能知道昨天的日期呢? 我应该用一减去它吗


共 (4) 个答案

  1. # 1 楼答案

    这对你来说应该很合适

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

    这将从当前日历日期减去1天,提供昨天的日期

  2. # 2 楼答案

    不,构建一个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);
    
  3. # 3 楼答案

    如果您在内部将时间戳存储为POSIX times(自1970年1月1日起的毫秒),那么您可以在任何时间戳上添加或减去一天,只要:

    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有足够的能力处理大多数本地时间转换,而无需您太多麻烦

  4. # 4 楼答案

    另一种方法是用SQL进行计算。根据您使用的数据库平台的不同,该语句可能会有所不同

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