【问题标题】:If I have an array of dates, how do I parse the months from each of those dates? [closed]如果我有一组日期,我如何解析每个日期的月份? [关闭]
【发布时间】:2013-07-13 14:59:44
【问题描述】:

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;
}

【问题讨论】:

  • 你在哪里声明了month数组?
  • Month 数组在类的开头声明 private int [] month
  • month 未在发布的代码中的任何位置声明
  • 那么,您的问题是什么?您发布的他的代码有任何问题吗?哪个问题?
  • 好吧,hd1 发布的代码返回的结果是 Date 而不是 int 数组。但我的问题是如何从日期数组中解析月份并将其存储到 int 月份数组中。

标签: java datetime


【解决方案1】:

好的,这就是我的答案,但我希望我们在 cmets 中进行的冗长对话能够让您了解如何通过仔细阅读堆栈跟踪、异常类型和消息来找到异常原因。

当你声明一个变量时,它不引用任何东西:

private int[] month;

等价于

private int[] month = null;

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

另外,由于month只用在方法中,所以不应该声明为字段,而是声明为局部变量:

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;
}

【讨论】:

    【解决方案2】:

    使用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;
    }
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-28
      • 2021-01-26
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      相关资源
      最近更新 更多