将字符串解析为日期

时间:2012-12-03 14:14:53

标签: java string parsing date typeconverter

String str_date = currentMonth + 1 + "-" + value.toString() + "-" + currentYear;
            DateFormat formatter ; 
            Date date = null ; 
            formatter = new SimpleDateFormat("dd-MMM-yy");
            try {
                date = (Date)formatter.parse(str_date);
            } 
            catch (ParseException e) {
                e.printStackTrace();
            }  
            System.out.println(date);

嗨,我试图搜索字符串到目前为止几乎每个人都使用这种代码,但似乎仍然打印出null?谢谢。

1 个答案:

答案 0 :(得分:0)

尝试

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

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

取决于你真正想要的东西。您的代码建议您可能希望将月份作为模式的第一部分。

确保currentMonth + 1符合您的要求。如果currentMonth为12,那么+1会将日期推迟到明年的1月。

另外,尝试习惯使用Locale。默认的一个可能适合你,但会打破别人的电脑。

相关问题