4

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
Rahul Babu
  • 730
  • 1
  • 5
  • 25

3 Answers3

6

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).

Henry
  • 42,982
  • 7
  • 68
  • 84
5

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • sadly my project is in java 7 . do java 7 give some API to which i give +0530 and it returns IST – Rahul Babu Apr 28 '16 at 13:27
  • 3
    You can't generally get the timezone name from a timezone offset, because there are many names using the same offset. – Andreas Apr 28 '16 at 13:32
  • 1
    @RahulBGangwar A time zone is an offset-from-UTC *plus* a set of rules for handling anomalies such as Daylight Saving Time. The [database of time zones](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) already lists two zones sharing the same offset of +05:30. Tomorrow there may be more. Each may have different rules. Also, stop using 3-4 letter codes like "IST", as they are neither standardized nor unique (Irish Standard Time, India …). Use proper name with an official definition and history, `Asia/Colombo`, `Asia/Kolkata`, `Europe/Dublin`. – Basil Bourque Apr 29 '16 at 17:58
0

Just to answer myself so that it might help some one else :

I was having date as string as input lets say :

String startDate = "2016-04-21T00:00:00+0530"
//i can calculate the timezone offset using
String offSet = startDate.substring(startDate.length() - 5) //gives +0530

Method used to calculate timezone. Here we give offset calculated above and the below method returns the TimeZone object:

public static TimeZone fetchTimeZone(String offset) {
        if (offset.length() != 5) {
            return null
        }

        TimeZone tz

        Integer offsetHours = Integer.parseInt(offset.substring(0, 3))
        Integer offsetMinutes = Integer.parseInt(offset.substring(3))

        String[] ids = TimeZone.getAvailableIDs()

        for (int i = 0; i < ids.length; i++) {
            tz = TimeZone.getTimeZone(ids[i])

            long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset())
            long minutes = Math.abs(TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset()) % 60)

            if (hours != offsetHours || minutes != offsetMinutes) {
                tz = null
            } else {
                break
            }
        }
        return tz
    }

Finally i use the Timezone from above method to format any date to that timezone :

SimpleDateFormat timeZonedFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
TimeZone timeZone = fetchTimeZone(offSet) //from above method and offset from first code
timeZonedFormatter.setTimeZone(timeZone);
//this timeZonedFormatter can be used to format any date into the respective timeZone
Rahul Babu
  • 730
  • 1
  • 5
  • 25