设置日历并添加1天

时间:2014-09-29 03:03:21

标签: android android-calendar

我有一个字符串(例如星期三10月15日),然后我必须在今天的第二天。我有一个方法,我用来做这个,但在本月之后,它会抛出错误的日期。这是方法:

public String getNextDay(String lastDate) {
    String[] wholedate = lastDate.split("\\s+");
    String datemon = wholedate[0];
    String date = wholedate[1];
    String dateday = wholedate[2];

    Calendar cal = Calendar.getInstance();
    cal.setFirstDayOfWeek(Calendar.SUNDAY);
    SimpleDateFormat df = new SimpleDateFormat("MMM dd cccc");

    int dayNo=0;
    if (dateday.equalsIgnoreCase("Sunday")) {
        dayNo = Calendar.SUNDAY;
    } else if (dateday.equalsIgnoreCase("Monday")) {
        dayNo = Calendar.MONDAY;
    } else if (dateday.equalsIgnoreCase("Tuesday")) {
        dayNo = Calendar.TUESDAY;
    } else if (dateday.equalsIgnoreCase("Wednesday")) {
        dayNo = Calendar.WEDNESDAY;
    } else if (dateday.equalsIgnoreCase("Thursday")) {
        dayNo = Calendar.THURSDAY;
    } else if (dateday.equalsIgnoreCase("Friday")) {
        dayNo = Calendar.FRIDAY;
    } else if (dateday.equalsIgnoreCase("Saturday")) {
        dayNo = Calendar.SATURDAY;
    }

    int monNo = 0;
    if (datemon.equalsIgnoreCase("Jan")) {
        monNo = Calendar.JANUARY;
    } else if (datemon.equalsIgnoreCase("Feb")) {
        monNo = Calendar.FEBRUARY;
    } else if (datemon.equalsIgnoreCase("Mar")) {
        monNo = Calendar.MARCH;
    } else if (datemon.equalsIgnoreCase("Apr")) {
        monNo = Calendar.APRIL;
    } else if (datemon.equalsIgnoreCase("May")) {
        monNo = Calendar.MAY;
    } else if (datemon.equalsIgnoreCase("Jun")) {
        monNo = Calendar.JUNE;
    } else if (datemon.equalsIgnoreCase("Jul")) {
        monNo = Calendar.JULY;
    } else if (datemon.equalsIgnoreCase("Aug")) {
        monNo = Calendar.AUGUST;
    } else if (datemon.equalsIgnoreCase("Sep")) {
        monNo = Calendar.SEPTEMBER;
    } else if (datemon.equalsIgnoreCase("Oct")) {
        monNo = Calendar.OCTOBER;
    } else if (datemon.equalsIgnoreCase("Nov")) {
        monNo = Calendar.NOVEMBER;
    } else if (datemon.equalsIgnoreCase("Dec")) {
        monNo =Calendar.DECEMBER;
    }

    cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date));
    cal.set(Calendar.MONTH, monNo);
    cal.set(Calendar.DAY_OF_WEEK, dayNo);

    cal.add(Calendar.DATE, 1);
    String fd = df.format(cal.getTime());

    return fd;
}

也许我将日期设置错误或者我需要为日期设置更多,或者可能有更好的方法来执行此操作。非常感谢你。

3 个答案:

答案 0 :(得分:0)

如果我是你,我会这样做

Calendar c = Calendar.getInstance();

c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

SimpleDateFormat df = new SimpleDateFormat("EEEE dd-MMM-yyyy", Locale.ENGLISH);

c.add(Calendar.DATE, 1); 

String nextDate = df.format(c.getTime());

答案 1 :(得分:0)

我的简单解决方案是调用Calendar.getTimeInMillis()来获取UTC时间戳,向其添加24x60x60x1000毫秒,然后将其放入另一个日历中。

此方法无需其他额外步骤。它应该是没有错误的,尽管效率可能有点差。但是,我把简单作为第一要务。

答案 2 :(得分:0)

我终于知道如何做到这一点,不设定星期几。由于某种原因,它混淆了约会。所以现在,我只设置day_of_month和月,我工作正常。谢谢你们。