Java简单日期格式 [英] Java Simple Date Format
问题描述
我正在尝试将文本格式化为日期。这是我有的:
I am trying to format text into a date. Here is what I have:
String pattern = "yyyy.MM.dd";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date d=sdf.parse("12.1.5");
我得到:
java.lang.IllegalArgumentException:此时,非法模式字符'Y'
java.lang.IllegalArgumentException: Illegal pattern character 'Y'
我也尝试使用ParsePosition以及2012.01.05。同样的错误。
I have also tried using a ParsePosition as well as "2012.01.05". Same error.
如何将此字符串解析成日期?任何可选的方式?我失踪了什么
How can I parse this string into a date? Any optional ways? What am I missing?
谢谢,
推荐答案
- 尽管您声称,您将拥有4位数字的年份,2位数字,然后是2位数字,然后提供2-1-1即可。
The code you've given works fine - although the fact that you're claiming you'll have a 4 digit year, 2 digit month and then 2 digit day, and then providing 2-1-1 is pretty ropy.
鉴于您遇到的异常,我怀疑您的模式实际上是 YYYY.MM.dd
这在 Java 7 中有效,其中 Y
表示周年,但不 Java 6 ,它不支持 Y
作为格式说明符 - 仅 y
。
Given the exception you're getting, I suspect that your pattern is actually "YYYY.MM.dd"
instead. That's valid in Java 7 where Y
means "week year" but it's not valid in Java 6 which doesn't support Y
as a format specifier - only y
.
即使有效,您也不希望 Y
这里 - 你只会指定周年,当你也指定星期的星期和星期几,你不在这里。
Even when it's valid, you really don't want Y
here - you would only specify week years when you're also specifying the week-of-week-year and day-of-week, which you're not doing here.
坚持您发布的代码中实际获得的模式,但请确保您的数据实际匹配...
Stick to the pattern you've actually got in the code you posted - but make sure your data actually matches it...
这篇关于Java简单日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!