有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何将“20201220T00:00:00.000Z”转换为java。util。日期

我试着用

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(d.toString(), formatter);

但它抛出了一个错误

有没有办法转换JSON默认时间戳


共 (5) 个答案

  1. # 1 楼答案

    这似乎是默认格式,请尝试此格式

    ZonedDateTime dateTime  = ZonedDateTime.parse("2020-07-28T14:28:52.877Z");
    
    // In case you still need LocalDateTime
    LocalDateTime localDateTime  = dateTime.toLocalDateTime();
    
    
  2. # 2 楼答案

    您不需要DateTimeFormatter来解析日期时间字符串

    将给定的日期字符串直接解析为OffsetDateTime。现代日期时间API基于ISO 8601,只要日期时间字符串符合ISO 8601标准,就不需要显式使用DateTimeFormatter对象。日期时间字符串中的^{cd4>}是零时区偏移的timezone designator。它代表Zulu并指定Etc/UTC时区(其时区偏移量为+00:00小时)

    OffsetDateTime odt = OffsetDateTime.parse("2020-12-20T00:00:00.000Z");
    

    OffsetDateTime转换为Instant

    使用^{}OffsetDateTime转换为Instant。一个^{}代表时间线上的一个瞬时点。它独立于时区,因此始终以UTC为单位

    Instant instant = odt.toInstant();
    

    停止使用旧的日期时间API

    随着2014年3月Java SE 8的发布,过时且容易出错的遗留日期时间API(java.util日期时间类型及其格式类型,SimpleDateFormat等)被java.time取代,即modern date-time API*。强烈建议停止使用旧API,并切换到这个新API。如果需要java.util.Date,请使用^{}获取它

    java.util.Date date = Date.from(instant);
    

    注意java.util.Date对象不是像modern date-time types那样的实时对象;相反,它表示自被称为“历元”的标准基准时间(即January 1, 1970, 00:00:00 GMT(或UTC))以来的毫秒数。打印java.util.Date的对象时,其toString方法返回JVM时区中的日期时间,根据该毫秒值计算。如果需要在不同的时区打印日期时间,则需要将时区设置为SimpleDateFormat,并从中获取格式化字符串,例如:

    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
    sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    System.out.println(sdf.format(date));
    

    可以将Instant转换为其他日期时间类型

    您可以轻松地将Instant转换为其他日期时间类型,例如,如果您想将其转换为表示伦敦日期时间的ZonedDateTime实例,您可以按以下方式进行转换:

    ZonedDateTime zdt = instant.atZone(ZoneId.of("Europe/London"));
    

    LocalDateTime对你来说没用

    Quoted below是对LocalDateTime用法的一个很好的描述:

    This class can be used to represent a specific event, such as the first race for the Louis Vuitton Cup Finals in the America's Cup Challenger Series, which began at 1:10 p.m. on August 17, 2013. Note that this means 1:10 p.m. in local time.

    日期时间字符串的最佳用途是作为OffsetDateTime,这是您在第一步中获得的

    演示:

    import java.time.Instant;
    import java.time.LocalDateTime;
    import java.time.OffsetDateTime;
    import java.time.ZoneId;
    import java.time.ZoneOffset;
    import java.time.ZonedDateTime;
    import java.util.Date;
    
    public class Main {
        public static void main(String[] args) {
            // Parse the date-time string into OffsetDateTime
            OffsetDateTime odt = OffsetDateTime.parse("2020-12-20T00:00:00.000Z");
            System.out.println(odt);
    
            // Convert OffsetDateTime into Instant
            Instant instant = odt.toInstant();
    
            // If at all, you need java.util.Date
            Date date = Date.from(instant);
            System.out.println(date);
    
            // You can convert an `Instant` to other date-time types easily
            // e.g. to ZoneDateTime in a specific timezone
            ZonedDateTime zdt = instant.atZone(ZoneId.of("Europe/London"));
            System.out.println(zdt);
    
            // e.g. to OffsetDateTime with a specific timezone offset
            OffsetDateTime odt0530 = instant.atOffset(ZoneOffset.of("-05:30"));
            System.out.println(odt0530);
    
            // e.g. to LocalDateTime via an OffsetDateTime or a ZonedDateTime
            LocalDateTime ldt = odt.toLocalDateTime();
            System.out.println(ldt);
        }
    }
    

    输出:

    2020-12-20T00:00Z
    Sun Dec 20 00:00:00 GMT 2020
    2020-12-20T00:00Z[Europe/London]
    2020-12-19T18:30-05:30
    2020-12-20T00:00
    

    了解更多关于^{cd15>},来自Trail: Date Timemodern date-time API*


    *无论出于何种原因,如果您必须坚持使用Java 6或Java 7,您可以使用ThreeTen-Backport来支持大部分Java。Java 6&;的时间功能;7.如果您正在为Android项目工作,并且您的Android API级别仍然不符合Java-8,请选中Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

  3. # 3 楼答案

    关于如何将LocalDate转换为java.util.Date的问题,可以使用Date.from方法,如下所示。让我知道这是否是你期望实现的目标

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
    LocalDate localDate = LocalDate.parse("2020-12-20T00:00:00.000Z", formatter);
    Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    System.out.println(date);
    
  4. # 4 楼答案

    你需要使用LocalDateTime

    DateTimeFormatter formatter = 
            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
    LocalDateTime date = LocalDateTime.parse(d.toString(), formatter);
    
  5. # 5 楼答案

    {}是祖鲁时区(即UTC时区),而不是字面上的Z

    整个格式是ISO-8601即时格式

    有一个预先存在的格式化程序:DateTimeFormatter#ISO_INSTANT

    摘自javadoc:

    public static final DateTimeFormatter ISO_INSTANT

    The ISO instant formatter that formats or parses an instant in UTC, such as '2011-12-03T10:15:30Z'.

    This returns an immutable formatter capable of formatting and parsing the ISO-8601 instant format. When formatting, the second-of-minute is always output. The nano-of-second outputs zero, three, six or nine digits digits as necessary. When parsing, time to at least the seconds field is required. Fractional seconds from zero to nine are parsed. The localized decimal style is not used.

    This is a special case formatter intended to allow a human readable form of an Instant. The Instant class is designed to only represent a point in time and internally stores a value in nanoseconds from a fixed epoch of 1970-01-01Z. As such, an Instant cannot be formatted as a date or time without providing some form of time-zone. This formatter allows the Instant to be formatted, by providing a suitable conversion using ZoneOffset.UTC.

    The format consists of:

    The ISO_OFFSET_DATE_TIME where the instant is converted from ChronoField.INSTANT_SECONDS and ChronoField.NANO_OF_SECOND using the UTC offset. Parsing is case insensitive.

    The returned formatter has no override chronology or zone. It uses the STRICT resolver style.