代码之家  ›  专栏  ›  技术社区  ›  Arvind Katte

Java 8:ZoneDateTime不支持enum Month,但它将接受包含enum Month的DataTime对象

  •  0
  • Arvind Katte  · 技术社区  · 8 年前

    我在做 ZonedDateTime 在向 ZonedDateTime.of(1990,Month.JANUARY,20,10,20,30,400,zoneId); ,不需要 Month.JANUARY 作为论据,但当我通过 DateTime 反对 enum Month.JANUARY ,它会很好用的。为什么? ZonedDateTime.of() 方法将不支持 枚举月。一月 .

    将来,他们是否会添加支持 ZonedDateTime.of 方法 枚举月。一月

    例子:

    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 回复  |  直到 8 年前
        1
  •  1
  •   Pankaj Singhal    8 年前

    签名 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)
    

    如你所见, 分区约会时间。of() 第二个arg int month 接受 int ,你不能通过考试 Month 实例。

    但是 LocalDateTime。of() 第二个arg Month month 接受 .

    如果你想用 在里面 分区约会时间。of() ,你可以通过 Month.JANUARY.getValue() 这个 getValue() 函数返回一个 智力 在范围内 1-12 ,这是月份arg的有效范围 分区约会时间。of() .下面的例子很好:

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