Java ResultSet how to getTimeStamp in UTC

前端 未结 2 1875
难免孤独
难免孤独 2021-01-01 23:39

The database has data in UTC and when I try to get data

java.util.Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone(\"UTC\"));
jav         


        
相关标签:
2条回答
  • 2021-01-02 00:17

    Your DateFormat instance is most likely displaying the value in local time. When displaying your value, give this a try:

    java.util.Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    java.sql.Timestamp ts = resultSet.getTimestamp(PUBLISH_TIME);
    cal.setTime(ts);
    
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(sdf.format(cal.getTime()));
    

    EDIT: to your comment:

    What if I use GMT, would that be an issue in SimpleDateFormat

    SimpleDateFormat can use general timezones (GMT +/- n), RFC822, and text ("if they have names" as the JavaDoc states - see this post for info on the names).

    0 讨论(0)
  • 2021-01-02 00:18
    java.util.Calendar cal = Calendar.getInstance(); 
    cal.setTimeZone(TimeZone.getTimeZone("UTC")); 
    java.sql.Timestamp ts = resultSet.getTimestamp(PUBLISH_TIME, cal); 
    

    This should do the trick!

    0 讨论(0)
提交回复
热议问题