Java 如何从字符串值创建日期对象

Java 如何从字符串值创建日期对象,java,date-format,simpledateformat,date-formatting,Java,Date Format,Simpledateformat,Date Formatting,当运行下面的代码时,我得到一个不可解析的日期异常 我该如何解决这个问题 package dateWork; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateCreation { /** *

当运行下面的代码时,我得到一个
不可解析的日期异常

我该如何解决这个问题

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

    }

您在月份中使用了错误的日期格式,并且应该使用与日期中相同的分隔符

如果日期字符串的格式为“2013/01/03”

对模式“yyyy/MM/dd”

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

在模式中使用相同的分隔符“-”
“yyyy-MM-dd”

应该是

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

嗯--->一年中的一个月

嗯-->每小时几分钟

String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 
您使用的模式与正在解析的模式不同

将其初始化为
DateFormat df=new SimpleDateFormat(“yyyy-MM-dd”)
或者这是
String startDateString=“2013/03/26”


MM
而不是
MM

-
而不是
/

ie
yyyy-MM-dd
在日期字符串中使用
-

在SimpleDataFormat的构造函数中传递相同格式的字符串(“yyyy-MM-dd”)

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

如果您的日期为“2013/03/26”,请使用


SimpleDateFormat(“yyyy/mm/dd”)

提示其中有两种日期格式,但只有一种SimpleDateFormat
-
String startDateString=“2013-03-26”;DateFormat df=新的简化格式(“yyyy-MM-dd”)
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");