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

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

问题描述

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

 String userDateFormat = "HHmm 'hrs', EEEE, MMMM dd, YYYY";SimpleDateFormat userDateFormatter = new SimpleDateFormat(userDateFormat);String reference_date = "2000 小时,星期四,2015 年 7 月 20 日";日期日期=空;尝试 {日期 = userDateFormatter.parse(reference_date);} catch (ParseException e) {System.out.println("日期格式为" + userDateFormat);}System.out.println(userDateFormatter.format(date));

以下方法块打印:2000 小时,2015 年 1 月 1 日,星期四.知道为什么吗?

解决方案

因为你在需要 yyyy 时使用了 YYYY 而 2015 年 7 月 20 日是星期一.你想要类似的东西

String userDateFormat = "HHmm 'hrs', EEEE, MMMM dd, yyyy";SimpleDateFormat userDateFormatter = new SimpleDateFormat(用户日期格式);String reference_date = "2000 小时,星期一,2015 年 7 月 20 日";

然后输出

2000 小时,2015 年 7 月 20 日,星期一

然后 SimpleDateFormat Javadoc 说(部分)

<块引用>

字母日期或时间组件表示示例G 时代指示符文本 ADy 年 1996 年;96Y 周年 2009 年;09

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

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

解决方案

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";

which then outputs

2000 hrs, Monday, July 20, 2015

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,月份为一月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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