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

Categories

0 votes
1.1k 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...