在Java中解析Youtube API日期

10

Youtube API中上传日期的格式是什么?我可以在SimpleDateFormat中使用什么格式?

例如 "2013-03-31T16:46:38.000Z"

P.S. 找到的解决方案是 yyyy-MM-dd'T'HH:mm:ss.SSSX

谢谢


SimpleDateFormat 能够解析你提供给它的几乎任何日期字符串。你只需要告诉它期望的格式即可。此外,我相信 Apache Commons Lang 还具有某些日期解析能力,这可能会简化事情。 - CodeChimp
我也是这么想的,但是java.text.ParseException: Unparseable date: "2013-03-31T16:46:38.000Z" - Serhii Bohutskyi
1个回答

3

这是一个ISO 8061日期时间

实际上,在Java8中,解析它非常简单,因为有预定义的DateTimeFormatter。这里是一个小的单元测试作为演示:

import org.junit.Test;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import static org.junit.Assert.assertEquals;

public class DateTimeFormatterTest {

    @Test
    public void testIsoDateTimeParse() throws Exception {
        // when
        final ZonedDateTime dateTime = ZonedDateTime.parse("2013-03-31T16:46:38.000Z", DateTimeFormatter.ISO_DATE_TIME);

        // then
        assertEquals(2013, dateTime.getYear());
        assertEquals(3, dateTime.getMonthValue());
        assertEquals(31, dateTime.getDayOfMonth());
        assertEquals(16, dateTime.getHour());
        assertEquals(46, dateTime.getMinute());
        assertEquals(38, dateTime.getSecond());
        assertEquals(ZoneOffset.UTC, dateTime.getZone());
    }
}

在Java8之前,我会查看将符合ISO 8601标准的字符串转换为java.util.Date,并且肯定会默认使用Joda Time,例如:

final org.joda.time.DateTime dateTime = new org.joda.time.DateTime.parse("2013-03-31T16:46:38.000Z");

顺便提一下,不要使用new DateTime("2013-03-31T16:46:38.000Z"),因为它会使用您的默认时区,这可能不是您想要的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接