我正在读取可能带有或不带有时区调整的日期字符串:yyyyMMddHHmmssz
或yyyyMMddHHmmss
. 当字符串缺少区域时,我会将其视为 GMT。我没有看到任何在 a 中创建可选部分的方法SimpleDateFormat
,但也许我遗漏了一些东西。有没有办法用 a 来做到这一点SimpleDateFormat
,或者我应该写一个新的混凝土DateFormat
来处理这个?
7 回答
JSR-310 随 Java 8 一起交付,它为解析时间值提供了增强的支持,其中组件现在可能是可选的。您不仅可以使区域可选,还可以使时间组件可选,并为给定字符串返回正确的时间单位。
考虑以下测试用例。
public class DateFormatTest {
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"yyyy-MM-dd[[ ]['T']HH:mm[:ss][XXX]]");
private TemporalAccessor parse(String v) {
return formatter.parseBest(v,
ZonedDateTime::from,
LocalDateTime::from,
LocalDate::from);
}
@Test public void testDateTime1() {
assertEquals(LocalDateTime.of(2014, 9, 23, 14, 20, 59),
parse("2014-09-23T14:20:59"));
}
@Test public void testDateTime2() {
assertEquals(LocalDateTime.of(2014, 9, 23, 14, 20),
parse("2014-09-23 14:20"));
}
@Test public void testDateOnly() {
assertEquals(LocalDate.of(2014, 9, 23), parse("2014-09-23"));
}
@Test public void testZonedDateTime() {
assertEquals(ZonedDateTime.of(2014, 9, 23, 14, 20, 59, 0,
ZoneOffset.ofHoursMinutes(10, 30)),
parse("2014-09-23T14:20:59+10:30"));
}
}
这里的DateTimeFormatter模式"yyyy-MM-dd[[ ]['T']HH:mm[:ss][XXX]]"
允许方括号内的选项也可以嵌套。模式也可以从DateTimeFormatterBuilder构造,上面的模式在这里演示:
private final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.optionalStart()
.optionalStart()
.appendLiteral(' ')
.optionalEnd()
.optionalStart()
.appendLiteral('T')
.optionalEnd()
.appendOptional(DateTimeFormatter.ISO_TIME)
.toFormatter();
这将转换为如下所示的表达式:
yyyy-MM-dd[[' ']['T']HH:mm[':'ss[.SSS]]].
可选值可以嵌套,如果仍然打开,最后也会自动关闭。但是请注意,没有办法在可选部分上提供异或,因此上述格式实际上可以很好地解析以下值:
2018-03-08 T11:12
请注意我们可以重用现有格式化程序作为我们当前格式的一部分的真正巧妙的功能。
我知道这是一个旧帖子,但只是为了记录......
Apache DateUtils 类可以帮助您。
String[] acceptedFormats = {"dd/MM/yyyy","dd/MM/yyyy HH:mm","dd/MM/yyyy HH:mm:ss"};
Date date1 = DateUtils.parseDate("12/07/2012", acceptedFormats);
Date date2 = DateUtils.parseDate("12/07/2012 23:59:59", acceptedFormats);
链接到 Maven 存储库中的Apache Commons Lang库,您可能想查看最新版本: http:
//mvnrepository.com/artifact/org.apache.commons/commons-lang3
Maven v3.4
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
摇篮 v3.4
'org.apache.commons:commons-lang3:3.4'
我会创建两个 SimpleDateFormat,一个有时区,一个没有。您可以查看 String 的长度来确定使用哪一个。
听起来您需要一个委托给两个不同 SDF 的 DateFormat。
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"));
如果您可以使用 Joda Datetime,它支持格式化程序中的可选部分,例如“yyyy-MM-dd [hh:mm:ss]”
private DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.append(DateTimeFormat.forPattern("yyyy-MM-dd"))
.appendOptional(
new DateTimeFormatterBuilder()
.appendLiteral(' ')
.append(DateTimeFormat.forPattern("HH:mm:ss"))
.toParser()
.toFormatter();
我将DateFormat
使用一个操作循环遍历潜在对象列表,try-catch
以在第一次成功解析时中断循环。
您可以创建两个不同的SimpleDateFormats
喜欢
public PWMDateTimeFormatter(String aPatternStr)
{
_formatter = DateTimeFormat.forPattern(aPatternStr);
}
public PWMDateTimeFormatter(String aPatternStr, TimeZone aZone)
{
_formatter = DateTimeFormat.forPattern(aPatternStr).withZone(XXDateTime._getTimeZone(aZone));
}
前段时间我通过扩展 SimpleDateFormat 解决了类似的问题。下面是一个粗略的实现来展示我的解决方案的想法。它可能没有完全完成/优化。
public class MySimpleDateFormat extends SimpleDateFormat {
private static final long serialVersionUID = 1L;
private static String FORMAT = "
private static int FORMAT_LEN = "yyyyMMddHHmmss".length();
private static String TZ_ID = "GMT";
public MySimpleDateFormat() {
this(TimeZone.getTimeZone(TZ_ID));
}
public MySimpleDateFormat(TimeZone tz) {
super(FORMAT);
setTimeZone(tz);
}
@Override
public Date parse(String source, ParsePosition pos) {
// TODO: args validation
int offset = pos.getIndex() + FORMAT_LEN;
Date result;
if (offset < source.length()) {
// there maybe is a timezone
result = super.parse(source, pos);
if (result != null) {
return result;
}
if (pos.getErrorIndex() >= offset) {
// there isn't a TZ after all
String part0 = source.substring(0, offset);
String part1 = source.substring(offset);
ParsePosition anotherPos = new ParsePosition(pos.getIndex());
result = super.parse(part0 + TZ_ID + part1, anotherPos);
if(result == null) {
pos.setErrorIndex(anotherPos.getErrorIndex());
} else {
// check SimpleDateFormat#parse javadoc to implement correctly the pos updates
pos.setErrorIndex(-1);
pos.setIndex(offset);
}
return result;
}
// there's something wrong with the first FORMAT_LEN chars
return null;
}
result = super.parse(source + TZ_ID, pos);
if(result != null) {
pos.setIndex(pos.getIndex() - TZ_ID.length());
}
return result;
}
public static void main(String [] args) {
ParsePosition pos = new ParsePosition(0);
MySimpleDateFormat mySdf = new MySimpleDateFormat();
System.out.println(mySdf.parse("20120622131415", pos) + " -- " + pos);
pos = new ParsePosition(0);
System.out.println(mySdf.parse("20120622131415GMT", pos) + " -- " + pos);
pos = new ParsePosition(0);
System.out.println(mySdf.parse("20120622131415xxx", pos) + " -- " + pos);
pos = new ParsePosition(0);
System.out.println(mySdf.parse("20120x22131415xxx", pos) + " -- " + pos);
}
}
要点是您需要检查输入字符串并以某种方式“猜测” TZ 字段是否丢失,如果是则添加它,然后让SimpleDateFormat#parse(String, ParsePosition)
其余的工作。上面的实现没有根据 javadoc 中的合同更新 ParsePositionSimpleDateFormat#parse(String, ParsePosition)
该类有一个默认 ctor,因为只允许一种格式。
该方法MySimpleDateFormat#parse(String, ParsePosition)
由调用,SimpleDateFormat#parse(String)
因此足以涵盖这两种情况。
运行 main() 这是输出(如预期的那样)
Fri Jun 22 14:14:15 BST 2012 -- java.text.ParsePosition[index=14,errorIndex=-1]
Fri Jun 22 14:14:15 BST 2012 -- java.text.ParsePosition[index=17,errorIndex=-1]
Fri Jun 22 14:14:15 BST 2012 -- java.text.ParsePosition[index=14,errorIndex=-1]
null -- java.text.ParsePosition[index=0,errorIndex=5]