本文介绍了从Java中的字符串解析日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串解析为Date对象,作为程序加载功能的一部分,如下所示:

I'm trying to parse a String to a Date Object, as part of a loading functionality for my program, as seen below:

    String dateString = "Wed Jan 18 23:22:18 EST 2017";
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz YYYY");
    try {
        Date scheduleItemDate = sdf.parse(dateString);
        System.out.println(scheduleItemDate.toString());
    }
    catch (ParseException e) {
        System.out.println("Exception");
    }

尽管日期应该与上面的dateString中的日期相同,但是程序会打印出以下日期:

Although the date should be the same as in dateString above, the program prints out the following date:

    Wed Jan 04 23:22:18 EST 2017

上述日期基本上比原日期晚了整整两个星期,我不确定我是怎么得到的,我做错了什么吗?

The above date is basically two full weeks behind the original date, I'm not sure as to how I am getting this, anything I am doing wrong?

推荐答案

小时应为 HH ,而不是 hh

年份应该是 yyyy 而不是 YYYY

始终先咨询 JavaDocs

String dateString = "Wed Jan 18 23:22:18 EST 2017";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
try {
    Date scheduleItemDate = sdf.parse(dateString);
    System.out.println(dateString);
    System.out.println(scheduleItemDate.toString());
    System.out.println(sdf.format(scheduleItemDate));
} catch (ParseException e) {
    System.out.println("Exception");
}

现在打印哪个...

Wed Jan 18 23:22:18 EST 2017
Wed Jan 18 23:22:18 EST 2017
Wed Jan 18 23:22:18 EST 2017

这篇关于从Java中的字符串解析日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:19