-1

I have a timestamp string which comes from a MS SQL server database. Its value is 2021-04-11 10:25:33.000, sql data type is datetime and time zone is PST i.e. pacific time. How do I convert this timestamp to UTC with Java? My expected result is 2021-04-11T17:25:33.000 which is UTC.

NOTE - I want to use only use Java 8 time libraries i.e. in the package java.time. I don't want Calendar, Date, SimpleDateFormat etc.

PS - Initially, I tried to find a solution on stack overflow, but could not find anything for a few minutes. All the top searches for my question gave solutions in php, c# and javascript.

MasterJoe
  • 2,103
  • 5
  • 32
  • 58
  • 2
    Does this answer your question? [Date in to UTC format Java](https://stackoverflow.com/questions/20238280/date-in-to-utc-format-java) – Trevor Kropp Apr 15 '21 at 04:27
  • @TrevorKropp - No. I tried this solution and it did not work https://stackoverflow.com/a/58580395/6648326. Its unable to parse the input timestamp because it has a space instead of T. Moreover, when I put a T there & ZoneId = America/Los_Angeles, I still get back my original time. I want my expected result instead. – MasterJoe Apr 15 '21 at 05:14
  • 1
    Don’t get your time stamp as a string from MS SQL. Retrieve a `LocalDateTime`. – Ole V.V. Apr 15 '21 at 05:31
  • @OleV.V. - The time stamp comes from results of a manually executed query. Btw, I answered my question below. I was wondering if you could please review it and give me feedback. – MasterJoe Apr 15 '21 at 05:32

2 Answers2

2

I combined two stack overflow posts to get the answer I need. It would be nice to get a review of my answer.

1 - I found one partially working solution here https://stackoverflow.com/a/34605826/6648326, but it drops the trailing zeros in my timestamp.

2 - Here is the answer to fix the trailing zeros problem https://stackoverflow.com/a/48043948/6648326

Working solution:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Temp {
    public static void main(String [] args){
        //America/Los_Angeles
        ZoneId usaPacific = ZoneId.of("America/Los_Angeles");
        String str = "2021-04-11 10:25:33.000";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        LocalDateTime localDateTime = LocalDateTime.parse(str, formatter);
        ZonedDateTime dateAndTimeInLosAngeles = ZonedDateTime.of(localDateTime, usaPacific );

        //2021-04-11T10:25:33-07:00[America/Los_Angeles]
        System.out.println("Current date and time in a particular timezone : " + dateAndTimeInLosAngeles);

        ZonedDateTime utcDate = dateAndTimeInLosAngeles.withZoneSameInstant(ZoneOffset.UTC);

        DateTimeFormatter formatterOut = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
        //2021-04-11T17:25:33Z
        System.out.println("Current date and time in UTC : " + utcDate.format(formatterOut));
    }
}
MasterJoe
  • 2,103
  • 5
  • 32
  • 58
  • 1
    If you cannot avoid getting the time stamp as a string, this is the right way to convert. Your JDBC `ResultSet` should give you a `LocalDateTime` directly, though. See for example [my answer here](https://stackoverflow.com/a/54907501/5772882). – Ole V.V. Apr 15 '21 at 05:42
0
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class GetUTCTime {

    // 取得本地时间:
    private Calendar cal = Calendar.getInstance();
    // 取得时间偏移量:
    private int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
    // 取得夏令时差:
    private int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);

    public static void main(String[] args) {
        GetUTCTime gc = new GetUTCTime();
        long mill = gc.getUTCTimeStr();
        gc.setUTCTime(mill);

    }

    public long getUTCTimeStr() {

        System.out.println("local millis = " + cal.getTimeInMillis()); // 等效System.currentTimeMillis() , 统一值,不分时区

        // 从本地时间里扣除这些差量,即可以取得UTC时间:
        cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));

        long mills = cal.getTimeInMillis();
        System.out.println("UTC = " + mills);

        return mills;
    }

    public void setUTCTime(long millis) {

        cal.setTimeInMillis(millis);

        SimpleDateFormat foo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = foo.format(cal.getTime());
        System.out.println("GMT time= " + time);

        // 从本地时间里扣除这些差量,即可以取得UTC时间:
        cal.add(java.util.Calendar.MILLISECOND, (zoneOffset + dstOffset));
        time = foo.format(cal.getTime());
        System.out.println("Local time = " + time);

    }

    public void getGMTTime() {
        //mothed 2
        TimeZone gmtTime = TimeZone.getTimeZone("GMT");
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        format.setTimeZone(gmtTime);
        System.out.println("GMT Time: " + format.format(date));
        
        //method 2
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeZone(gmtTime);
        //System.out.println(calendar1.getTime());    //时区无效
        //System.out.println(calendar1.getTimeInMillis()); //时区无效
        System.out.println("GMT hour = " + calendar1.get(Calendar.HOUR));
    }
}
  • 2
    This is not useful for me because its not using Java 8 time libraries. – MasterJoe Apr 15 '21 at 05:12
  • 2
    The OP explicitly wisely said *I don't want Calendar, Date, SimpleDateFormat etc.* And even if not, please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Apr 15 '21 at 05:30
  • @OleV.V. ! yes sir! my english not good! i see "How to convert a datetime string into UTC in Java?" so i put that code on there! sry for that! V_V – 时间只会一直走 Apr 15 '21 at 05:32