在java中解析字符串到日期格式默认为1和月到1月 [英] Parsing a string to date format in java defaults date to 1 and month to January

查看:528
本文介绍了在java中解析字符串到日期格式默认为1和月到1月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以下列格式接受日期的用户输入:2000小时,2015年7月20日星期四。然后我会将其转换为日期格式以对其进行操作。但是从字符串到日期的转换是默认月份到1月,日期为1.以下是代码片段:

I am trying to accept a user input of date in the format like : "2000 hrs, Thursday, July 20, 2015". I will then convert this to a date format to do operations on it. But the convertion from string to date is defaulting month to January and date to 1. Here is the code snippet :

    String userDateFormat = "HHmm 'hrs', EEEE, MMMM dd, YYYY";
    SimpleDateFormat userDateFormatter = new SimpleDateFormat(userDateFormat);
    String reference_date = "2000 hrs, Thursday, July 20, 2015";

    Date date = null;
    try {
        date = userDateFormatter.parse(reference_date);
    } catch (ParseException e) {
        System.out.println("Date must be in the format " + userDateFormat);
    }

    System.out.println(userDateFormatter.format(date));

以下方法块打印:
2000小时,2015年1月1日,星期四。
有什么线索?

The following method block prints : 2000 hrs, Thursday, January 01, 2015. Any clue why?

推荐答案

因为您使用 YYYY 时你需要 yyyy ,2015年7月20日是星期一。你想要像

Because you used YYYY when you needed yyyy and July 20, 2015 was a Monday. You wanted something like

String userDateFormat = "HHmm 'hrs', EEEE, MMMM dd, yyyy";
SimpleDateFormat userDateFormatter = new SimpleDateFormat(
        userDateFormat);
String reference_date = "2000 hrs, Monday, July 20, 2015";

然后输出

2000 hrs, Monday, July 20, 2015

然后 SimpleDateFormat Javadoc说(部分)

Then SimpleDateFormat Javadoc says (in part)


Letter    Date or Time Component  Presentation    Examples
G         Era designator          Text            AD
y         Year                    Year            1996; 96
Y         Week year               Year            2009; 09


这篇关于在java中解析字符串到日期格式默认为1和月到1月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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