如何将字符串值转换为日期对象

3
运行以下代码时,我遇到了一个“UNPARSABLE DATE EXCEPTION”的异常。
我该如何解决这个问题?
   package dateWork;

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class DateCreation {

        /**
         * @param args
         */
        public static void main(String[] args) {

            String startDateString = "2013-03-26";
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 
            Date startDate=null;
            String newDateString = null;
            try 
            {
                startDate = df.parse(startDateString);
                newDateString = df.format(startDate);
                System.out.println(startDate);
            } catch (ParseException e) 
            {
                e.printStackTrace();
            }
        }

    }

1
提示您有两种日期格式,但只有一个SimpleDateFormat。 - Kevin D
1
尝试使用“-”:String startDateString = "2013-03-26"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); - Alya'a Gamal
4个回答

12

您使用了错误的月份日期格式,同时应该使用与日期相同的分隔符。

如果您的日期字符串格式为"2013/01/03"

请在模式"yyyy/MM/dd"中使用相同的分隔符/

如果您的日期字符串格式为"2013-01-03"

请在模式"yyyy-MM-dd"中使用相同的分隔符 '-'。

    DateFormat df = new SimpleDateFormat("yyyy/mm/dd"); 

应该是

    DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 

SimpleDateFormat文档

MM--->年中的月份

mm--->小时中的分钟数


1

MM代替mm

-代替/ 例如,由于日期字符串中使用了-,因此应该使用yyyy-MM-dd


1
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 

您正在使用与正在解析的模式不同的模式。

要么将其初始化为DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 要么将其初始化为String startDateString = "2013/03/26";

此文章也值得一看


0

在SimpleDateFormat构造函数中传递相同格式的字符串("yyyy-mm-dd")

因为您的日期字符串是"2013-03-26"

如果您的日期字符串是"2013/03/26",请使用

SimpleDateFormat("yyyy/mm/dd")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接