問題描述
我正在讀取可能帶有或不帶有時區調整的日期字符串:yyyyMMddHHmmssz
或 yyyyMMddHHmmss
.當字符串缺少區域時,我會將其視為 GMT.我沒有看到在 SimpleDateFormat
中創建可選部分的任何方法,但也許我遺漏了一些東西.有沒有辦法用 SimpleDateFormat
來做到這一點,還是我應該寫一個新的具體 DateFormat
來處理這個?
I'm reading in date strings that could be with or without a time zone adjustment: yyyyMMddHHmmssz
or yyyyMMddHHmmss
. When a string is missing a zone, I'll treat it as GMT. I'm not seeing any way to create optional sections in a SimpleDateFormat
, but maybe I'm missing something. Is there a way to do this with a SimpleDateFormat
, or should I just write a new concrete DateFormat
to handle this?
推薦答案
我會創建兩個 SimpleDateFormat,一個有時區,一個沒有.您可以查看 String 的長度來確定使用哪一個.
I would create two SimpleDateFormat, one with a time zone and one without. You can look at the length of the String to determine which one to use.
聽起來您需要一個代表兩個不同 SDF 的 DateFormat.
Sounds like you need a DateFormat which delegates to two different SDF.
DateFormat df = new DateFormat() {
static final String FORMAT1 = "yyyyMMddHHmmss";
static final String FORMAT2 = "yyyyMMddHHmmssz";
final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1);
final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2);
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
throw new UnsupportedOperationException();
}
@Override
public Date parse(String source, ParsePosition pos) {
if (source.length() - pos.getIndex() == FORMAT1.length())
return sdf1.parse(source, pos);
return sdf2.parse(source, pos);
}
};
System.out.println(df.parse("20110102030405"));
System.out.println(df.parse("20110102030405PST"));
這篇關于SimpleDateFormat 中的可選部分的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!