Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get time zone from date

Tags:

java

datetime

I am trying to get time zone from an existing date to use it for some other date conversion. Can someone reply with updating the todos in the below code. Appreciate any help.

Or just to make it simple is there some java api to which i give +0530 and it returns IST :)

Here is my code :

import java.text.SimpleDateFormat
import java.util.*;
import java.text.DateFormat;

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = isoFormat.parse("2016-04-21T00:00:00+0530");

//todo print time zone 
//todo here should print IST since date is having +0530
like image 354
Rahul Babu Avatar asked Oct 19 '25 01:10

Rahul Babu


2 Answers

This is not possible. A Date does not have time zone information attached. It is just a point in time, internally represented as milliseconds since 1.1.1970 midnight UTC (excluding leap seconds).

like image 141
Henry Avatar answered Oct 20 '25 15:10

Henry


A java.util.Date does not have a time zone. It is a pure time in UTC. The parser converted the string to the internal value.

A java.time.ZonedDateTime (Java 8+) does have a time zone.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssZ");
ZonedDateTime dt = ZonedDateTime.parse("2016-04-21T00:00:00+0530", formatter);
ZoneId zone = dt.getZone();

If running Java 6 or 7, use the backport of the Java SE 8 date-time classes.
For Java 5+ use the Joda-Time library.

like image 35
Andreas Avatar answered Oct 20 '25 14:10

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!