我目前在我的应用程序中使用Joda时间日期API。我正在使用以下代码将多种日期格式解析为一个单一的格式。但是,当日期格式中没有年份时,我遇到了问题。当前,它会将年份设置为“2000”。
如果日期格式中缺少年份,是否有一种方法将年份设置为默认值?
private static final DateTimeParser[] parsers = {
DateTimeFormat.forPattern("dd/MMM/yyyy:HH:mm:ss Z").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").getParser(),
DateTimeFormat.forPattern("[dd/MMM/yyyy:HH:mm:ss Z]").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").getParser(),
DateTimeFormat.forPattern("MMM-dd HH:mm:ss,SSS").getParser()
};
public static DateTime ConvertDate(String timestamp) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
DateTime date = formatter.parseDateTime(timestamp);
return date;
}
示例:
Mar-07 13:59:13,219
转换为:
当前年份-03-07T12:59:13.219-07:00
说明:
需要将日期格式从月-日 时:分:秒,毫秒 转换为 ISO 8601 格式,即:年-月-日 T 时:分:秒.毫秒 偏移量。其中,偏移量表示与协调世界时的时差,例如北京时间为东八区,偏移量为 +08:00。