在日期工作中出现问题


I want to convert String to date object I used this code to convert
  try{
            SimpleDateFormat parse = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
            String dateTime = "1996-10-7T4:50:00Z";
        Date parsed = parse.parse(dateTime);
            System.out.println("formatted: " + formatter.format(parsed));
            }
            catch(ParseException e){
            System.out.println("Caught " + e);
            }
output:

I need value of date object to be **1996-10-7T4:50:00Z** as it as the given string.

但以上代码产生日期对象:Mon Oct 07 04:50:00 PDT 1996

试一下:

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ");

使用相同的对象进行解析和格式化。

看这个,你肯定会得到答案的

SimpleDateFormat

当我运行上面的代码时,我收到了这样的输出:

格式:1996 - 10 - 07 - t04:50:00z

Date对象本身没有格式化。格式化程序完成这项工作。当我运行你的代码时,我得到:

formatted: 1996-10-07T04:50:00Z

很好。

EDIT: btw duffymo是正确的,如下:您不需要有两个不同的格式化器

最新更新