Java 8:ZonedDateTime将不支持枚举月,但它将接受包含枚举月的DataTime对象

时间:2018-07-28 06:03:33

标签: enums java-8 zoneddatetime

在将参数传递给ZonedDateTime时,我正在ZonedDateTime.of(1990,Month.JANUARY,20,10,20,30,400,zoneId);上工作,它不会以Month.JANUARY作为参数,但是当我传递DateTime对象时使用enum Month.JANUARY,它将正常工作。为什么ZonedDateTime.of()方法不支持enum Month.JANUARY

将来,他们会添加ZonedDateTime.of来支持enum Month.JANUARY方法的方法吗

示例:

package com.katte.infa;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class DateTimeDemo {

public static void main(String[] args) {
    LocalDateTime dateTime1 = LocalDateTime.of(1990, 1, 1,12,20,20);
    System.out.println("DateTime1:" +dateTime1);

    LocalDateTime dateTime2 = LocalDateTime.of(1990, Month.JANUARY, 1,12,20,20); // enum Month.JANUARY
    System.out.println("DateTime2:" +dateTime2);

    ZoneId zoneId = ZoneId.systemDefault();

    ZonedDateTime zdateTime1 = ZonedDateTime.of(dateTime1,zoneId);
    ZonedDateTime zdateTime2 = ZonedDateTime.of(dateTime2,zoneId); // enum Month.JANUARY, works fine

    System.out.println("ZdateTime1 :" +zdateTime1);
    System.out.println("ZdateTime2 :" +zdateTime2);

    ZonedDateTime zdateTime3 = ZonedDateTime.of(1990,10,20,10,20,30,400,zoneId);
    ZonedDateTime zdateTime4 = ZonedDateTime.of(1990,Month.JANUARY,20,10,20,30,400,zoneId); // not compile 
}
}

1 个答案:

答案 0 :(得分:1)

LocalDateTime.of()的签名如下:

public static LocalDateTime of(int year, Month month, int dayOfMonth,
                               int hour, int minute, int second)

ZonedDateTime.of()的值为:

public static ZonedDateTime of(
        int year, int month, int dayOfMonth,
        int hour, int minute, int second, int nanoOfSecond, ZoneId zone)

如您所见,ZonedDateTime.of()的第二个参数int month接受一个int,您无法在其中传递一个Month实例。

但是LocalDateTime.of()的第二个参数Month month接受Month

如果要在Month中使用ZonedDateTime.of(),则可以通过Month.JANUARY.getValue()使用它。 getValue()函数返回int范围内的1-12,该范围是ZonedDateTime.of()月份的有效范围。以下示例可以正常工作:

ZonedDateTime.of(1990, Month.JANUARY.getValue(),20,10,20,30,400,null);