如果当前日期以字符串形式给出,如何找到上一个日期?

时间:2012-01-20 11:44:41

标签: java date

如果以字符串形式提供当前日期,如何找到上一个日期?下面给出了我的代码。有没有更短的解决方案?

   private static String previousDay(String date) {
        String[] ymd = date.split("-");
        int year = Integer.parseInt(ymd[0]);
        int month = Integer.parseInt(ymd[1]);
        int day = Integer.parseInt(ymd[2]);
        String newDate = "";
        if (day > 1 & month > 1)
            newDate = year+"-"+month+"-"+(day-1);
        else if (day == 1 & month > 1) {
            Calendar calendar = new GregorianCalendar(year,month-1, 1);
            int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            newDate = year+"-"+(month-1)+"-"+daysInMonth;
        } else if (day == 1 & month == 1) {
            Calendar calendar = new GregorianCalendar(year,12, 1);
            int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            newDate = year+"-"+12+"-"+daysInMonth;
        }
        return newDate;
    }

3 个答案:

答案 0 :(得分:3)

您需要将String转换为Date,以便进行日期计算。您可以使用日历查找前一天。我假设您的代码来自您的代码,您的日期格式为yyyy-MM-dd。

String input = "2009-09-30";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = dateFormat.parse(input);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(myDate);
cal1.add(Calendar.DAY_OF_YEAR, -1);
Date previousDate = cal1.getTime();

答案 1 :(得分:1)

Date currentDate= new Date();

Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);

Date previousDate = calendar.getTime();

答案 2 :(得分:0)

// dccTimeStamp is "20120122121212"
String dccTimeStamp is "20120122121212"
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Date dcc = sdf.parse(dccTimeStamp);
log.debug("Dcc Date is " + dcc.toString());

从此时起,您可以使用日期(或日历)实用程序并执行所需的日期操作。