problems with Java daylight savings time

后端 未结 4 1152
长情又很酷
长情又很酷 2021-01-05 01:35

I have a Java app that needs to be cognizant of the time zone. When I take a Unix epoch time and try to convert it into a timestamp to use for an Oracle SQL call, it is get

4条回答
  •  我在风中等你
    2021-01-05 02:18

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.TimeZone;
    
    public class TimeZoneTest {
        public static void main(String[] argv) throws ParseException {
    
            SimpleDateFormat formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
    
            String dateInString = "22-01-2015 10:15:55 AM";
            Date date = formatter.parse(dateInString);
            TimeZone tz = TimeZone.getDefault();
    
            // From TimeZone Asia/Singapore
            System.out.println("TimeZone : " + tz.getID() + " - " + tz.getDisplayName());
            System.out.println("TimeZone : " + tz);
            System.out.println("Date : " + formatter.format(date));
    
            // To TimeZone America/New_York
            SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
            TimeZone tzInAmerica = TimeZone.getTimeZone("America/New_York");
            sdfAmerica.setTimeZone(tzInAmerica);
    
            String sDateInAmerica = sdfAmerica.format(date); // Convert to String first
            Date dateInAmerica = formatter.parse(sDateInAmerica);
    
            System.out.println("\nTimeZone : " + tzInAmerica.getID() + 
                                          " - " + tzInAmerica.getDisplayName());
            System.out.println("TimeZone : " + tzInAmerica);
            System.out.println("Date (String) : " + sDateInAmerica);
            System.out.println("Date (Object) : " + formatter.format(dateInAmerica)); 
        }
    
    }
    

提交回复
热议问题