如何从String值创建Date对象 [英] how to create Date object from String value

查看:99
本文介绍了如何从String值创建Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当运行以下代码时,我得到一个 UNPARSABLE DATE EXCEPTION

When running through the below code I am getting an 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();
            }
        }

    }


推荐答案

您在月份中使用了错误的dateformat,也应使用与日期相同的分隔符。

You used wrong dateformat for month, also you should use the same delimiter as in your date.

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

If you date string is of format "2013/01/03"

对模式yyyy / MM / dd使用相同的分隔符 /

use the same delimiter / for the pattern "yyyy/MM/dd"

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

If your date string is of format "2013-01-03"

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

use the same delimiter '-' in your pattern "yyyy-MM-dd"

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

应该是

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

来自SimpleDateFormat Doc

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

MM---> month in an year

mm --->小时分钟

mm---> minutes in hour

这篇关于如何从String值创建Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆