如何在java中获取上一个日期

如何在java中获取上一个日期,java,date,Java,Date,我有一个格式为yyyyMMdd的字符串对象。有没有一种简单的方法可以获得具有相同格式的上一个日期的字符串? 谢谢使用SimpleDateFormat解析到目前为止的字符串,然后减去一天。之后,再次将日期转换为字符串。如果没有库支持,这比在Java中要困难得多 可以使用类的实例将给定字符串解析为日期对象 然后你可以用日历减去一天 然后,您可以使用SimpleDataFormat将格式化日期获取为字符串 这是一个简单得多的API。以下是如何在没有Joda时间的情况下完成此操作: import jav

我有一个格式为yyyyMMdd的字符串对象。有没有一种简单的方法可以获得具有相同格式的上一个日期的字符串?
谢谢

使用SimpleDateFormat解析到目前为止的字符串,然后减去一天。之后,再次将日期转换为字符串。

如果没有库支持,这比在Java中要困难得多

可以使用类的实例将给定字符串解析为日期对象

然后你可以用日历减去一天

然后,您可以使用SimpleDataFormat将格式化日期获取为字符串

这是一个简单得多的API。

以下是如何在没有Joda时间的情况下完成此操作:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {

    public static String previousDateString(String dateString) 
            throws ParseException {
        // Create a date formatter using your format string
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        // Parse the given date string into a Date object.
        // Note: This can throw a ParseException.
        Date myDate = dateFormat.parse(dateString);

        // Use the Calendar class to subtract one day
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(myDate);
        calendar.add(Calendar.DAY_OF_YEAR, -1);

        // Use the date formatter to produce a formatted date string
        Date previousDate = calendar.getTime();
        String result = dateFormat.format(previousDate);

        return result;
    }

    public static void main(String[] args) {
        String dateString = "20100316";

        try {
            // This will print 20100315
            System.out.println(previousDateString(dateString));
        } catch (ParseException e) {
            System.out.println("Invalid date string");
            e.printStackTrace();
        }
    }
}

我会重写一下这些答案

你可以用

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

        // Get a Date object from the date string
        Date myDate = dateFormat.parse(dateString);

        // this calculation may skip a day (Standard-to-Daylight switch)...
        //oneDayBefore = new Date(myDate.getTime() - (24 * 3600000));

        // if the Date->time xform always places the time as YYYYMMDD 00:00:00
        //   this will be safer.
        oneDayBefore = new Date(myDate.getTime() - 2);

        String result = dateFormat.format(oneDayBefore);
要获得与使用日历计算的结果相同的结果。

我想在20天前,到目前为止

 Calendar cal = Calendar.getInstance();
    Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR, - 20);

System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
我在1月11日尝试时得到了一些意想不到的结果

当前时间2011年1月11日星期二12:32:16 X时间2010年12月11日星期六12:32:16

Calendar cal = Calendar.getInstance();
Calendar xdate = (Calendar)cal.clone();
xdate.set(Calendar.DAY_OF_YEAR,cal.getTime().getDate() - 20 );

System.out.println(" Current Time "+ cal.getTime().toString());
System.out.println(" X Time "+ xdate.getTime().toString());
此代码解决了我的问题。

您可以使用:

Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.YEAR, -1);
Date dt2 = new Date(cal2.getTimeInMillis());
System.out.println(dt2);
    Calendar cal  = Calendar.getInstance();
    //subtracting a day
    cal.add(Calendar.DATE, -1);

    SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
    String result = s.format(new Date(cal.getTimeInMillis()));

如果您愿意使用第三方实用程序,下面是一些在Java7上使用JodaTime2.3的示例代码。只需要两行

String dateAsString = "20130101";
org.joda.time.LocalDate someDay =  org.joda.time.LocalDate.parse(dateAsString, org.joda.time.format.DateTimeFormat.forPattern("yyyymmdd"));
org.joda.time.LocalDate dayBefore = someDay.minusDays(1);
请参见结果:

System.out.println("someDay: " + someDay );
System.out.println("dayBefore: " + dayBefore );
运行时:

someDay: 2013-01-01
dayBefore: 2012-12-31
此代码假定您没有时区。缺少时区很少是一件好事,但如果这是你的情况,那么代码可能适合你。如果您确实有时区,请使用对象而不是

关于那个示例代码和关于Joda时间

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/

// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310

// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601

您可以创建一个通用方法,该方法

   - Date (String)  (current date or from date),
   - Format (String) (your desired fromat) and
   - Days (number of days before(-ve value) or after(+ve value))
作为输入并以所需格式返回所需日期

下面的方法可以解决这个问题

public String getRequiredDate(String date , String format ,int days){
        try{
         final Calendar cal = Calendar.getInstance();
            cal.setTime(new SimpleDateFormat(format).parse(date));
            cal.add(Calendar.DATE, days);
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            date = sdf.format(cal.getTime());
        }
        catch(Exception ex){
            logger.error(ex.getMessage(), ex);
        }
        return date;
    }
}

这是一个老问题,大多数现有答案都是在Java8之前的。因此,为Java 8+用户添加此答案。


Java8为
Date
Time
引入了新的API,以取代设计拙劣、难以使用的
Java.util.Date
Java.util.Calendar

要处理没有时区的日期,可以使用
LocalDate

String dateString = "20200301";

// BASIC_ISO_DATE is "YYYYMMDD"
// See below link to docs for details
LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.BASIC_ISO_DATE);

// get date for previous day
LocalDate previousDate = date.minusDays(1);

System.out.println(previousDate.format(DateTimeFormatter.BASIC_ISO_DATE));
// prints 20200229
文件:


不是一个直接的答案,但请稍后再看一看。对于Java来说,它是一个非常好的日期/时间库——try块中的大多数代码甚至不会抛出ParseException。您应该限制其范围。这是一个稍微简单的示例。这是我这样做的唯一原因…谢谢!这个例子很有用。我使用了:DateFormat DateFormat=newsimpledateformat(“yyyyMMdd”);Calendar cal=新的GregorianCalendar()。cal.setTime(dateFormat.parse(strDate));cal.add(日历日/年-1);strDate=dateFormat.format(cal.getTime());您没有使用Calendar.getInstance()的具体原因是什么?为了安全起见,我会在构建/获取日历后直接调用
calendar.clear()
,以避免时区冲突。此方法似乎在输入“0000101”时遇到问题。只有当DST干扰时,您才会遇到问题。您的代码可能会在同一天返回。。。