Setting values of Java Calendar does not give expected date-time

后端 未结 5 1121
谎友^
谎友^ 2021-01-02 02:25

I have an hour, minute, date and millisecond timestamp, and am trying to create a Date object representing the time. The timestamp is provided in Eastern Daylight Time.

5条回答
  •  情书的邮戳
    2021-01-02 02:48

    I would simply set the time zone first:

     Calendar cal = GregorianCalendar.getInstance();
    
        cal.clear();
        cal.setTimeZone(TimeZone.getTimeZone("EDT"));
        cal.setTime(today);
        cal.set(Calendar.HOUR_OF_DAY,hour);
        cal.set(Calendar.MINUTE,min);
        cal.set(Calendar.SECOND,sec);
        cal.set(Calendar.MILLISECOND,ms);
    

    However it was doing what it should, as said in the comments 4am is 11pm in EST.

    And even better solution would be not to use Calendar at all but joda-time for instance.

    EDIT: This produces the right time for me.

        Date today = new Date();
        int hour = 4, min  = 0, sec  = 0, ms   = 64;
        boolean print = false;
    
        Calendar cal = GregorianCalendar.getInstance();
        if(print)
            System.out.println("After initializing, time is: "+cal.getTime());
        cal.clear();
        if(print)
            System.out.println("After clearing, time is: "+cal.getTime());
        cal.setTimeZone(TimeZone.getTimeZone("EDT"));
        if(print)
            System.out.println("After setting time zone, time is: "+cal.getTime());
        cal.setTime(today);
        if(print)
            System.out.println("After setting date, time is: "+cal.getTime());
        cal.set(Calendar.HOUR_OF_DAY,hour);
        if(print)
            System.out.println("After setting hour, time is: "+cal.getTime());
        cal.set(Calendar.MINUTE,min);
        if(print)
            System.out.println("After setting minute, time is: "+cal.getTime());
        cal.set(Calendar.SECOND,sec);
        if(print)
            System.out.println("After setting second, time is: "+cal.getTime());
        cal.set(Calendar.MILLISECOND,ms);
        if(print)
            System.out.println("After setting milliseconds, time is: "+cal.getTime());
    
        System.out.println("TIME: "+cal.getTime());
    

提交回复
热议问题