user-44651
user-44651

Reputation: 4124

Convert Local time to UTC with timezoneoffset in Java

I have a local date/timestamp and I have a timezone offset stored in String format (myStringTimeStamp variable name below). I need to convert the local date/timestamp to UTC time.

The format the timestamp is in is: yyyy-MM-dd HH:mm:ss

I have tried variations on:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);

sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

//Convert timestamp to date 
Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0)); 

newTimeStamp = sdf.format(d);

But I can't seem to figure out the right formula. Any help?

I can't use 3rd party libraries/frameworks.

Upvotes: 1

Views: 430

Answers (2)

dimplex
dimplex

Reputation: 494

Did you try:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);

    //Convert timestamp to date 
    Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0)); 

    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    newTimeStamp = sdf.format(d);

Upvotes: 1

Amila
Amila

Reputation: 5213

Problem seems to be because you're setting the target timezone before parsing.

First parse, then set timezone, and finally format.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);

//Convert timestamp to date 
Date d = sdf.parse(myStringTimeStamp, new ParsePosition(0)); 

sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

newTimeStamp = sdf.format(d);

Upvotes: 1

Related Questions