如果我有一系列日期,我如何解析每个日期的月份?

时间:2013-07-13 14:59:44

标签: java datetime

Month是一个int数组,用于解析Date数组中的每个月。

public int [] getMonth() throws ParseException{
        String [] date=getDate();
        DateFormat df= new SimpleDateFormat("MM.dd.yy hh:mm");
        Date [] result= new Date [date.length];

        for (int i=0; i<date.length; i++){
            Calendar cal= Calendar.getInstance();
            result[i]=df.parse(date[i]);
            cal.setTime(result[i]);
            month[i]=cal.get(Calendar.MONTH);
        }
        return month;
}

2 个答案:

答案 0 :(得分:0)

使用joda

public int [] getMonth(){
    String [] date=getDate();
    DateTimeFormatter df = DateTimeFormat.forPattern("MM.dd.yy hh:mm");
    DateTime result[] = new DateTime[date.length];
    int i = 0;
    for (Date d : date) {
       result[i] = df.parse(d).month().getAsText();
       i++;
    }
    return result;
}

希望有所帮助。

答案 1 :(得分:0)

好的,所以这是我的答案,但我希望通过仔细阅读堆栈跟踪,异常类型和消息,我们在评论中进行的冗长对话将学会如何找到异常的原因。

声明变量时,它不引用任何内容:

private int[] month;

相当于

private int[] month = null;

因此,您还没有任何数组,并且您无法在其中存储任何内容。为了能够使用它,必须对其进行初始化。

此外,由于月仅用于方法,因此不应将其声明为字段,而应将其声明为局部变量:

public int [] getMonth() throws ParseException{
    String [] date=getDate();
    int[] month = new int[date.length]; // here's the missing line
    DateFormat df= new SimpleDateFormat("MM.dd.yy hh:mm");
    Date [] result= new Date [date.length];

    for (int i=0; i<date.length; i++){
        Calendar cal= Calendar.getInstance();
        result[i]=df.parse(date[i]);
        cal.setTime(result[i]);
        month[i]=cal.get(Calendar.MONTH);
    }
    return month;
}