Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

datetime - Java Date Time conversion to given timezone

I have a DateTime in the format of Tue, 30 Apr 2019 16:00:00 +0800 which is RFC 2822 formatted date

I need to convert this to the given timezone in the DateTime which is +0800

So if i summarized,

DateGiven = Tue, 30 Apr 2019 16:00:00 +0800
DateWanted = 01-05-2019 00:00:00

How can i achieve this in Java? I have tried the below code but it gives 08 hours lesser than the current time which is

30-04-2019 08:00:00

Code i tried

String pattern = "EEE, dd MMM yyyy HH:mm:ss Z";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date startDate = format.parse(programmeDetails.get("startdate").toString());

//Local time zone   
 SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

//Time in GMT
Date dttt= dateFormatLocal.parse( dateFormatGmt.format(startDate) );
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are on right approach but just use java-8 date time API module, first create DateTimeFormatter with the input format representation

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z");

And then use OffsetDateTime to parse string with offset

OffsetDateTime dateTime = OffsetDateTime.parse("Tue, 30 Apr 2019 16:00:00 +0800",formatter);

And the call the toLocalDateTime() method to get the local time

LocalDateTime localDateTime = dateTime.toLocalDateTime();  //2019-04-30T16:00

If you want the output in particular format again you can use DateTimeFormatter

localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)   //2019-04-30T16:00:00

Note : As @Ole V.V pointed in comment, after parsing the input string into util.Date you are getting the UTC time

The class Date represents a specific instant in time, with millisecond precision.

So now if you convert the parsed date time into UTC you get 2019-04-30T08:00Z without offset, so you can use withOffsetSameInstant to convert it into any particular timezone

dateTime.withOffsetSameInstant(ZoneOffset.UTC)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...