简体   繁体   中英

how to get and format date with timezone

I'am creating a date and store it into database, I want to get current time which is timezone = "Asia/Istanbul" not my local time.

I am creating the date in my local computer, my local timezone is also "Asia/Istanbul".

when i deploy it into my server, server timezone is utc, it is turning to utc everytime.

I have different 2 machine, 2 machines have different timezone so I need to set my data dates with the timezone.

here is what i have done. it is ok in my local computer, but fails on server which is UTC

LocalDateTime localDateTime = LocalDateTime.now();
// it gives my local date time, 2019-07-09T10:30:03.171
// local date is now 1:30 pm, UTC is 3 hours after, it looks ok.
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Asia/Istanbul"));
//2019-07-09T10:30:03.171+03:00[Asia/Istanbul]
// it looks +3. I dont want to see +3, I want the date like 01:30 which is shiefted
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
zonedDateTime.format(formatter);
//2019-07-09T07:30:03.171Z
// zone is disappeared, this is 3 hours before UTC

I expect the date like Asia/Istanbul when i created it.

I wouldn't use LocalDateTime at all. Use ZonedDateTime throughout to eliminate any and all doubt about the time. Also always pass a ZoneId (if not a Clock ) to the now method. This makes your code independent of the time zone settings of the computer and JVM.

    ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Istanbul"));
    System.out.println(zonedDateTime);

2019-07-09T14:14:17.280852+03:00[Asia/Istanbul]

You might have misunderstood the +03:00 part, people sometimes do. It means that the time shown is already 3 hours ahead of UTC. So the point in time shown is equal to 11:14:17 UTC.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    System.out.println(zonedDateTime.format(formatter));

2019-07-09 14:14:17

Your formatter does not include time zone, therefore it's not shown. But it's the time in İstanbul.

What went wrong in your code?

I am assuming that the comments in your code are from running on your server in UTC (it's not perfectly clear) and that you ran the code around 10:30 UTC, the same as 13:30 in İstanbul.

A LocalDateTime is a date and time without time zone and without UTC offset. Its no-arg now method uses the JVM's time zone setting, in this case UTC, so gives you 10:30 on the day in question. I think that ZonedDateTime.of is wrong here: it takes the 10:30 from the LocalDateTime and İstanbul time zone from the ZoneId object and gives you 10:30 in İstanbul, which is not what you wanted. You had wanted 13:30, AKA 1:30 PM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM