【发布时间】:2017-09-26 06:16:08
【问题描述】:
在我的框架中,我需要在 Java 日期和 ASN1 UTC 时间(通用时间)之间进行转换。我试过 SimpleDateFormat 和 OffsetDateTime。有没有一种明确简单的方法来获得两个方向? asn1 中的字节是字符字节。例如下面,但是我需要以字节为单位的“YYMMDDhhmmssZ”。
解码测试通过,由于与第一个答案的变化,如下:
@Test
public void testUTCTimeDecode() throws IOException {
byte[] bytes = new byte[] {48, 55, 48, 51, 50, 50, 49, 53, 53, 56, 49, 55, 90};
ByteArrayInputStream derStream = new ByteArrayInputStream(bytes);
Date testDate = new Date(OffsetDateTime.parse("2007-03-22T15:58:17+00:00").toEpochSecond() * 1000);
byte[] decodeBytes = new byte[bytes.length];
derStream.read(decodeBytes);
OffsetDateTime actual = OffsetDateTime.parse(
new String(decodeBytes),
DateTimeFormatter.ofPattern("uuMMddHHmmssX"));
Date date = Date.from(actual.toInstant());
assertTrue(date.equals(testDate));
}
我仍然遇到编码问题。下面是抛出的异常和测试方法:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: Year
at java.time.Instant.getLong(Instant.java:603)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$NumberPrinterParser.format(DateTimeFormatterBuilder.java:2540)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2179)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1746)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1720)
at club.callistohouse.asn1.ASN1TestModel.testUTCTimeEncode(ASN1TestModel.java:47)
这是我正在使用的测试方法,现已修复。
@Test
public void testUTCTimeEncode() throws IOException {
byte[] bytes = new byte[] {48, 55, 48, 51, 50, 50, 49, 53, 53, 56, 49, 55, 90};
ByteArrayOutputStream derStream = new ByteArrayOutputStream();
Date testDate = new Date(OffsetDateTime.parse("2007-03-22T15:58:17+00:00").toEpochSecond() * 1000);
Instant instant = Instant.ofEpochMilli(testDate.getTime());
DateTimeFormatter utcFormatter = DateTimeFormatter
.ofPattern ( "uuMMddHHmmssX" )
.withLocale( Locale.US )
.withZone( ZoneId.of("UTC"));
String formattedDate = utcFormatter.format(instant);
derStream.write(formattedDate.getBytes());
assertTrue(Arrays.equals(bytes, derStream.toByteArray()));
}
【问题讨论】:
-
如果不知道您的
ASN1InputStream和ASN1OutputStream课程,就很难分辨。您可以生成Minimal, Complete, and Verifiable example 吗? -
由于您可以使用
OffsetDateTime,我建议您使用没有过时类Date、SimpleDateFormat和TimeZone的解决方案。 -
我修复了一个演员表问题,尽管解析格式的解码仍然失败。除了 testUTCTime 之外,我还启用了 testGeneralizedTime。
-
欢迎来到 Stack Overflow。如果您可以提供一个最小的、完整的和可验证的示例,包括精确的预期和观察到的输出,我们可能会帮助您,并且很乐意帮助您。
-
我编辑了 OP,感谢您帮助我解决了一个更好的问题,希望如此。