【问题标题】:calendar month and year before日历月份和年份之前
【发布时间】:2014-11-27 23:57:59
【问题描述】:

我必须在一周前和一个月前确定一个日期。如果我尝试使用一周前的几天工作,但如果第 5 天并且它必须更改月份不工作,它会改变我的年份。关于它改变我年份的月份 字符串 addUrl = "";

    SimpleDateFormat sdf = new SimpleDateFormat("dd.mm.yyyy");
    // surround below line with try catch block as below code throws checked
    // exception
    Date endDate = sdf.parse(request.getParameter(field.getId()));
    Calendar cal = DateToCalendar(endDate);
    cal.setTime(endDate);

    SimpleDateFormat formatToSend = new SimpleDateFormat("yyy-mm-dd");

    case "day":
        cal.add(Calendar.DATE, -1);

        addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
        break;

    case "week":
        cal.add(Calendar.DATE, -6); // number of days to add
        addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;
        break;

    default:
        cal.add(Calendar.MONTH, -1); // number of days to add
        addUrl = "startDate=" + formatToSend.format(cal.getTime()) + "&endDate=" + endDateString;

    }

我该怎么做?

谢谢

【问题讨论】:

标签: java date calendar


【解决方案1】:

在您的SimpleDateFormat 对象中,您应该使用MM 表示几个月而不是mm,因为mm 表示分钟,而不是几个月。

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");

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

参见java.text.SimpleDateFormat的API文档。

【讨论】:

    【解决方案2】:

    我不确定我是否完全理解这个问题,但是一个潜在的问题是你的日期格式

    m = 分钟以小时为单位

    M = 月份一年

    更多示例请参见此处。

    https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2011-01-11
      • 1970-01-01
      相关资源
      最近更新 更多