Convert UTC Date to local Date - java

I am converting from epoch time (which is in UTC) to a format as shown below. Now I tried different SO answers to convert UTCDate from UTC to local time. But I am not getting the local time.
Any help would be appreciated.
String epochTime = "1436831775043";
Date UTCDate = new Date(Long.parseLong(epochTime));
Date localDate; // How to get this?
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
String result = simpleDateFormat.format(UTCDate);
Also, the conversion has to be done without the help of any external library.

Java 8
String epochTime = "1436831775043";
Instant utcInstant = new Date(Long.parseLong(epochTime)).toInstant();
ZonedDateTime there = ZonedDateTime.ofInstant(utcInstant, ZoneId.of("UTC"));
System.out.println(utcInstant);
LocalDateTime here = there.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(here);
Which outputs:
2015-07-13T23:56:15.043Z
2015-07-14T09:56:15.043
After thoughts...
I think you're chasing your tail. Date is just a container for the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT). It doesn't internally carry a representation of a time zone (AFAIK).
For example...
String epochTime = "1436831775043";
Date UTCDate = new Date(Long.parseLong(epochTime));
// Prints the "representation" of the Date
System.out.println(UTCDate);
// Local date/time format...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
try {
System.out.println("local format: " + simpleDateFormat.format(UTCDate));
System.out.println("local Date: " + simpleDateFormat.parse(simpleDateFormat.format(UTCDate)));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication203.class.getName()).log(Level.SEVERE, null, ex);
}
// UTC date/time format
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("utc format: " + simpleDateFormat.format(UTCDate));
System.out.println("utc date: " + simpleDateFormat.parse(simpleDateFormat.format(UTCDate)));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication203.class.getName()).log(Level.SEVERE, null, ex);
}
Which outputs...
Tue Jul 14 09:56:15 EST 2015
local format: 14/07/2015 9:56:15 AM
local Date: Tue Jul 14 09:56:15 EST 2015
utc format: 13/07/2015 11:56:15 PM
utc date: Tue Jul 14 09:56:15 EST 2015
If you have a look at local Date and utc date they are the same thing, even though the local format and utc format are formatted correctly.
So, instead of chasing your tale trying to get Date to "represent" a value you want, either use Java 8's Time API or JodaTime to manage the Time Zone information or simply format the Date into the Time Zone you want...
Further, if we do something like...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
Date localDate = simpleDateFormat.parse(simpleDateFormat.format(UTCDate));
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = simpleDateFormat.parse(simpleDateFormat.format(UTCDate));
System.out.println(localDate.getTime());
System.out.println(utcDate.getTime());
System.out.println(localDate.equals(utcDate));
It will print...
1436831775000
1436831775000
true

You can set your time zone in the formatter:
simpleDateFormat.setTimeZone(TimeZone.getDefault());

Related

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) );
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)
You misunderstood. According to RFC 2822 +0800 means that an offset of 8 hours 0 minutes has already been applied to the time compared to UTC. So the output you got was the correct GMT time.
java.time
I recommend you skip the old and outdated classes SimpleDateFOrmat and Date. It’s much nicer to work with java.time, the modern Java date and time API. Furthermore it has the RFC format built in, so we don’t need to write our own formatter.
OffsetDateTime parsedDateTime = OffsetDateTime
.parse("Tue, 30 Apr 2019 16:00:00 +0800",
DateTimeFormatter.RFC_1123_DATE_TIME);
ZonedDateTime dateTimeInSingapore
= parsedDateTime.atZoneSameInstant(ZoneId.of("Asia/Singapore"));
System.out.println("In Singapore: " + dateTimeInSingapore);
OffsetDateTime dateTimeInGmt
= parsedDateTime.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println("In GMT: " + dateTimeInGmt);
Output:
In Singapore: 2019-04-30T16:00+08:00[Asia/Singapore]
In GMT: 2019-04-30T08:00Z
The built-in formatter is named RFC_1123_DATE_TIME because the same format is used in multiple Requests for Comments (RFCs).
Links
RFC 2822 Internet Message Format
Oracle tutorial: Date Time explaining how to use java.time.
with the help of #ole v.v's explanation i have separated the datetime value for two
1. time
2. timezone
then i used this coding to extract the datetime which is related to the given timezone
//convert datetime to give timezone
private static String DateTimeConverter (String timeVal, String timeZone)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(timeZone));
String result =null;
try {
result = offsetDateFormat2.format(format.parse(timeVal));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

SimpleDateFormat results in incorrect time

I have the following code
protected void amethod1() {
String strDate = "Thu May 18 16:24:59 UTC 2017";
String dateFormatStr = "EEE MMM dd HH:mm:ss zzz yyyy";
DateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
Date formattedDate = null;
try {
formattedDate = dateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
The resulting value of formattedDate is- "Thu May 18 11:24:59 CDT 2017" .
I am testing this code in Chicago and the local timezone is CDT.
I am not able to understand why the time value changes from 16:24:59 to 11:24:59 even though. Am I missing something in the defined format of the date?
Class Date doesn't contain any timezone at all. It's just a number of milliseconds since 01.01.1970 00:00:00 GMT. If you try to see, what formattedDate contains with System.out.println or debugger, you'll get formatted date for your local timezone. 11:24:59 CDT and 16:24:59 UTC are the same time, so result is correct.
Is java.util.Date using TimeZone?
It is better to use jodatime or Java 8 Time API in order to better manage time and timezones.
First, you are getting the correct time. When Daylight Savings Time is in use in Chicago (which it is on May 18), the time is 11:24:59 when it’s 16:24:59 in UTC. So your Date value represents the same point in time. This is all you can expect from a Date.
I understand that you want not just a point in time, but also the UTC time zone. Since Axel P has already recommended Java 8 date and time API, I just wanted to fill in the details:
DateTimeFormatter parseFormatter = DateTimeFormatter.ofPattern(dateFormatStr, Locale.US);
ZonedDateTime dateTime = ZonedDateTime.parse(strDate, parseFormatter);
The result is
2017-05-18T16:24:59Z[UTC]
If you always want the UTC time zone, the Instant class is just right for it, so you will probably want to convert to it:
Instant instant = dateTime.toInstant();
Instants are always in UTC, popularly speaking.
SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now=new Date();
System.out.println(myFmt.format(now));
I hope I can help you. If you can,please adopt.Thank you
The resulting value of formattedDate is- "Thu May 18 11:24:59 CDT 2017" . Why? because your time zone running -5 hour from UTC time you will find in below link wiki time zone abbreviations, if you want result in same timezone you need to specify timezone in formater Hope you get my concern
https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations
public static void amethod1() {
String strDate = "Thu May 18 16:24:59 UTC 2017";
String dateFormatStr = "EEE MMM dd HH:mm:ss zzz yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date formattedDate = null;
try {
formattedDate = dateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("formattedDate: "+dateFormat.format(formattedDate));
}
You specified timezone, that's why after parsing time on current timezone (where you are), SimpleDateFormat sets UTC timezone. When you try to output your date, it is displayed on your current timezone
It appears you would need to specify the TimeZone as well when you format the Date For eg. .TimeZone.setDefault(TimeZone.getTimeZone("PST"));
Have a look at this discussion TimeZone
The output of a Date depends on the format specified, where you can specify the timezone, as shown in the example below:
protected void amethod2() {
String strDate = "Thu May 18 16:24:59 UTC 2017";
String dateFormatStr = "EEE MMM dd HH:mm:ss zzz yyyy";
DateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
Date formattedDate = null;
try {
formattedDate = dateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Date: " + formattedDate);
// Thu May 18 17:24:59 BST 2017, BST is my system default timezone
// Set the time zone to UTC for the calendar of dateFormat
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Date in timezone UTC: " + dateFormat.format(formattedDate));
// Thu May 18 16:24:59 UTC 2017
// Set the time zone to America/Chicago
dateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println("Date in timezone America/Chicago: " + dateFormat.format(formattedDate));
// Thu May 18 11:24:59 CDT 2017
}
As for the IDs, such as "UTC" and "America/Chicago" in the example, you can get a complete list of them via TimeZone.getAvailableIDs(). You can print them out to have a look:
Arrays.stream(java.util.TimeZone.getAvailableIDs()).forEach(System.out::println);
And you'll have:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
Africa/Blantyre
...

Get correct long value from parsed Date (Timezone issue)

I'm trying to parse a date from a String and get the long value. The long value will be later sent to an SQL query.
here's my code:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date day = new Date();
try {
day = sdf.parse(dayDate);
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
which gives the following output:
day : Thu Feb 28 00:00:00 EET 2013 long : 1362002400000
which is correct but not what I want since the long value results in Wed, 27 Feb 2013 22:00:00 GMT (http://www.epochconverter.com/) (I'm in a GMT+2 timezone). And i need to send to correct long value to sql.
Is there anyway to work around this without using external libraries?
SimpleDateFormat is locale-aware, meaning the date it parses is in your timezone. Midnight 28 Feb in GMT+2 is actually 10pm 27 Feb in GMT, the long value 1362002400000. I would add this to get the parsing right (would't bother using Calendar):
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
Again, when you print this date it uses SimpleDateFormat and that's why you can see EET in the output.
Passing this to database is a different story though once you get this right.
Use DateFormat.setCalendar(Calendar cal) to set a Calendar with GMT as its timezone, or use DateFormat.setTimeZone(TimeZone zone) with the GMT TimeZone. That will ensure that the resulting Date will be 00:00:00 in GMT instead of in EET.
If you add a timezone specifier to your string you can force java to use GMT for the conversion:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy z"); // z is a timezone specifier
Date day = new Date();
try {
day = sdf.parse(dayDate + " GMT"); // Use GMT timezone.
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
You are converting between text and internal (Date) representations of dates and times without explicitly stating the time-zone. That never goes well.
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date date = calendar.getTime();
Use your timezone String:
TimeZones

Local date & time to UTC and then UTC to local date & time

I am trying to convert locale time to UTC, and then UTC to locale time. But I am not getting the result.
public class DateDemo
{
public static void main(String args[])
{
DateFormat dateFormatter =
DateFormat.getDateTimeInstance
(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
TimeZone.setDefault(TimeZone.getDefault());
SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat simpleTimeFormatter = new SimpleDateFormat("hh:mm:ss a");
Date today = new Date();
String localeFormattedInTime = dateFormatter.format(today);
try
{
Date parsedDate = dateFormatter.parse(localeFormattedInTime);
System.out.println("Locale:" + localeFormattedInTime);
System.out.println("After parsing a date: " + parsedDate);
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
String date = simpleDateFormatter.format(today);
String time = simpleTimeFormatter.format(today);
System.out.println("Today's only date: " + date);
System.out.println("Today's only time: " + time);
//// Locale to UTC converting
simpleDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
simpleTimeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcDate = simpleDateFormatter.format(today);
String utcTime = simpleTimeFormatter.format(today);
System.out.println("Convert into UTC's date: " + utcDate);
System.out.println("Convert into UTC's only time: " + utcTime);
//// UTC to locale converting
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
String getLocalDate = simpleDateFormatter.format(getDate);
String getLocalTime = simpleTimeFormatter.format(getTime);
System.out.println("Get local date: " + getLocalDate);
System.out.println("Get local time: " + getLocalTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I am sending local date & time to the web service, and then when require I need to retrieve the UTC date & time and then convert into locale date & time (i.e. user's local settings).
Sample Output:
Locale:11/9/12 8:15 PM
After parsing a date: Fri Nov 09 20:15:00 SGT 2012
Today's only date: 09/11/2012
Today's only time: 08:15:30 PM
Convert into UTC's date: 09/11/2012
Convert into UTC's only time: 12:15:30 PM
Get local date: 09/11/2012
Get local time: 12:15:30 PM
After Saksak & ADTC answers:
For the code fragment, UTC date & time (what is actually coming as GMT-5 because database may be in USA) is the input, and I want to get local date & time as output. But this following segment is still giving GMT-5 time.
SimpleDateFormat simpleDateTimeFormatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
....
Date inDateTime = simpleDateTimeFormatter.parse(intent.getExtras().getString("inTime")); Date outDateTime = simpleDateTimeFormatter.parse(intent.getExtras().getString("outTime"));
simpleDateTimeFormatter.setTimeZone(TimeZone.getDefault()); simpleDateTimeFormatter.setTimeZone(simpleDateTimeFormatter.getTimeZone());
//TimeZone tzTimeZone = TimeZone.getDefault();
//System.out.println("Current time zone: " + tzTimeZone.getDisplayName());
String getLocalInTimeString = simpleDateTimeFormatter.format(inDateTime);
String getLocalOutTimeString = simpleDateTimeFormatter.format(outDateTime);
My question: getLocalInTimeString & getLocalOutTimeString still showing GMT-5 timing. What's wrong here? Do I need to set any other things?
What you need to do to solve your problem is the following, you have your code to convert back to local time in this order :
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
and what you need to do is wait until you parse utcDate, utcTime Strings back to Date Object
then set the date formatter time zone to local zone as follows :
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
this should print the correct date/time in local.
Edit:
here is the full main method :
public static void main(String[] args) {
DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
TimeZone.setDefault(TimeZone.getDefault());
SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat simpleTimeFormatter = new SimpleDateFormat("hh:mm:ss a");
Date today = new Date();
String localeFormattedInTime = dateFormatter.format(today);
try {
Date parsedDate = dateFormatter.parse(localeFormattedInTime);
System.out.println("Locale:" + localeFormattedInTime);
System.out.println("After parsing a date: " + parsedDate);
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
String date = simpleDateFormatter.format(today);
String time = simpleTimeFormatter.format(today);
System.out.println("Today's only date: " + date);
System.out.println("Today's only time: " + time);
//// Locale to UTC converting
System.out.println("TimeZone.getDefault() >>> " + TimeZone.getDefault());
simpleDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
simpleTimeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcDate = simpleDateFormatter.format(today);
String utcTime = simpleTimeFormatter.format(today);
System.out.println("Convert into UTC's date: " + utcDate);
System.out.println("Convert into UTC's only time: " + utcTime);
//// UTC to locale converting
/**
** //////EDIT
*/
// at this point your utcDate,utcTime are strings that are formated in UTC
// so first you need to parse them back to Dates using UTC format not Locale
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
// NOW after having the Dates you can change the formatters timezone to your
// local to format them into strings
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
String getLocalDate = simpleDateFormatter.format(getDate);
String getLocalTime = simpleTimeFormatter.format(getTime);
System.out.println("Get local date: " + getLocalDate);
System.out.println("Get local time: " + getLocalTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
Your problem is in lines 54 and 55:
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
These lines are merely parsing Strings that contain the date and time, but these strings do not have any timezone information:
utcDate = "09/11/2012"
utcTime = "12:15:30 PM"
Therefore the parser assumes that the Strings are already in the locale of the timezone you set in lines 51 and 52.
Now think about how to fix it ;) HINT: Make sure the parser is assuming the correct timezone of the time represented by the strings.
PS: [RESOLVED!] I solved the problem but I discovered that the timezone conversion is erratic, for at least where I am. Time is 8:30 pm local. Convert to UTC, 12:30 pm (correct, 8 hr difference). Convert back, it's 8:00 pm (WRONG, eventhough the set timezone is correct - I got the original one and passed it back in - I'm only getting 7.5 hour difference). You should look for more reliable ways unless you can figure out what's going on and how to solve it.
[RESOLUTION:] The problem above was actually because the original code was splitting the date and time into two different parsers. If you use just one parser for both date and time combined you will get the correct date and time in the target locale. So in conclusion the parser is reliable but the way you use it makes a big difference!
SimpleDateFormat simpleDateTimeFormatter
= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date getDateTime
= simpleDateTimeFormatter.parse(utcDate + " " + utcTime);
//use above line if you have the date and time as separate strings
simpleDateTimeFormatter.setTimeZone(TimeZone.getDefault());
String getLocalDateTime = simpleDateTimeFormatter.format(getDateTime);
System.out.println("Get local date time: " + getLocalDateTime);
WHY USING TWO SEPARATE PARSERS FOR DATE AND TIME IS UNRELIABLE:
As explained above, it's a bad idea to use two separate parsers for date and time parts. Here's why:
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
//Time zone changed to local here
String getLocalDate2 = simpleDateTimeFormatter.format(getDate);
String getLocalTime2 = simpleDateTimeFormatter.format(getTime);
System.out.println("Get local date2: " + getLocalDate2);
System.out.println("Get local time2: " + getLocalTime2);
OUTPUT:
Get local date2: 10/11/2012 08:00:00 AM
Get local time2: 01/01/1970 10:35:10 AM
I get the half hour difference because the default date 01/01/1970 is used in the Date variable storing time (second line). When this is converted to local timezone, the error happens as the formatter bases its conversion on the default date 01/01/1970 (where I live, the time difference was +7.5 hours in 1970 - today, it is +8 hours). This is why two separate parsers is not reliable even if you get the right result and you must always use a combined parser that accepts both date and time information.

timezone conversion and date is not displaying properly

Calendar cal= Calendar.getInstance();
System.out.println(cal.getTimeZone().getID());
cal.set(2012, 8, 21);
java.util.Date d = new java.util.Date();
System.out.println(d.toString());
//System.setProperty("user.timezone", "America/Chicago");
// System.out.println(TimeZone.getDefault().getID());
TimeZone tz1 = TimeZone.getTimeZone("Africa/Algiers");
//tz1.setDefault(tz1);
cal.setTimeZone(tz1);
System.out.println(cal.getTimeZone().getID());
//cal.set(2012, 8, 21);
System.out.println(d.toString());
Output is --
Asia/Calcutta
Tue Aug 21 11:35:06 IST 2012
Africa/Algiers
Tue Aug 21 11:35:06 IST 2012
I want the time in the currrent timezone format but it is giving in IST. How to do this.
EDIT: I've only just noticed that the code you're given doesn't even call cal.getTime(). You're completely ignoring the value in the calendar. It wouldn't do what you wanted anyway, but the value you're printing is just new Date()... how do you expect the calendar to get involved?
I want the time in the currrent timezone format but it is giving in IST. How to do this.
Avoid using Date.toString, to start with. A Date value has no concept of a time zone, so toStringjust uses the system time zone, always. Changing the time zone of a calendar without calling set again doesn't change the underlying value, either.
Now there are two options:
Use SimpleDateFormat, specifying the time zone there before formatting
Use Joda Time instead, which is a much richer date and time API in the first place
Personally I'd strongly advise you to use the latter option, particularly if you're doing quite a bit of date/time manipulation. Date, Calendar and SimpleDateFormat just don't let you write code which clearly expresses what data you have at any point in time.
Use TimeZone.setDefault(tz1); instead of //tz1.setDefault(tz1);
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTimeZone().getID());
cal.set(2012, 8, 21);
java.util.Date d = new java.util.Date();
System.out.println(d.toString());
TimeZone tz1 = TimeZone.getTimeZone("Africa/Algiers");
TimeZone.setDefault(tz1);
cal.setTimeZone(tz1);
System.out.println(cal.getTimeZone().getID());
System.out.println(d.toString());
I run your program, see output :
Asia/Calcutta
Tue Aug 21 11:47:13 IST 2012
Africa/Algiers
Tue Aug 21 07:17:13 CET 2012
Calender doesnot work that way...i have SimpleDateFormat code..it may help..try this
public class TimeZoneTest {
public static void main(String[] args) {
new TimeZoneTest().setTimeZones();
}
private void setTimeZones(){
String etStart = "";
String ctStart = "";
String mtStart = "";
String ptStart = "";
DateFormat fullDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
String dateString = "Mon Mar 14 09:30:51 GMT 2011";
//this input date doesn't convert
//String dateString = "Mon Mar 14 09:30:51 PDT 2011";
System.out.println("Input Date: " + dateString);
System.out.println("Default TimeZone: " + TimeZone.getDefault());
try {
etStart = getDateInTimeZone(dateString, fullDateFormat, TimeZone.getTimeZone("America/New_York"));
ctStart = getDateInTimeZone(dateString, fullDateFormat, TimeZone.getTimeZone("America/Chicago"));
mtStart = getDateInTimeZone(dateString, fullDateFormat, TimeZone.getTimeZone("America/Denver"));
ptStart = getDateInTimeZone(dateString, fullDateFormat, TimeZone.getTimeZone("America/Los_Angeles"));
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Eastern Date: " + etStart);
System.out.println("Central Date: " + ctStart);
System.out.println("Mountain Date: " + mtStart);
System.out.println("Pacific Date: " + ptStart);
}
private String getDateInTimeZone(Date inputDt, TimeZone targetTimeZone) throws ParseException{
DateFormat fullDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
fullDateFormat.setTimeZone(targetTimeZone);
return fullDateFormat.format(inputDt);
}
}

Categories