我正在尝试将格式化的日期解析回Date对象,但我一直遇到异常,这是我的代码:
DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy ", Locale.ENGLISH);
date = dateFormat.parse(dateString);
当我尝试Apr 17, 2016
之类的日期时,我会ParserException
说Unparseable date: "Apr 17, 2016" (at offset 12)
答案 0 :(得分:2)
当您提供日期格式字符串时,所有字符必须以某种方式考虑dateString
中的所有文本,包括文字空格字符。
格式字符串末尾有空格字符:
"MMMM d, yyyy "
消除该空格(或在dateString
字符串末尾包含空格)。
The format strings MMMM
or MMM
will parse Apr
just fine
文字:格式化时,如果图案字母数为4或更多,则使用完整格式;否则,如果可用,则使用简短或缩写形式。对于解析,两种形式都被接受,与模式字母的数量无关。
答案 1 :(得分:2)
您的日期掩码中有一个小捆绑包:最后一个空白太多了:
DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy ", Locale.ENGLISH);
应该是:
DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
这就是错误指向“偏移12”的原因:DateFormat期望在该位置留空。
答案 2 :(得分:1)
您需要删除字符串格式的最后一个空格。
你真的有
class Calculation
attr_accesor :operands
end
module SumOperation
def sum
self.operands.sum
end
end
class MyCustomCalculation < Calculation
include SumOperation
end
它应该是
DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy ", Locale.ENGLISH);
答案 3 :(得分:0)
尝试以下
DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = dateFormat.parse(dateString);