timezone conversion and date is not displaying properly - java

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);
}
}

Related

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

(Android) How to convert a time raw string (with timezone) to another string format with the same timezone

I have a time raw string, "2016-05-15T12:42:00.000-04:00" and I want to convert the string to "Wed 15 May 2016 12:42", which keeps the same timezone (-04:00) as its original source.
I have tried SimpleDateFormat but using it returns different timezones that are not the same as the timezone in my original string. Please help me achieve this in Android Studio!
Other examples:
2016-05-15T15:42:00.000-08:00 -> Wed 15 May 2016 15:42
2016-05-15T14:44:00.000-01:00 -> Wed 15 May 2016 14:44
public static String formatDateString(String originDateString) {
//Original format 2016-05-15T12:42:00.000-04:00
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
SimpleDateFormat resultFormat = new SimpleDateFormat("EEE dd MMM yyyy HH:mm");
String dateString = "";
try {
Date date = originalFormat.parse(originDateString);
dateString = resultFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
//returned format: Tue 14 May 2016 12:42
return dateString;
}
try saving it first without the TZ information
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

Why does my SimpleDateFormat parsing not work?

I need help parsing the String date
"Thu Oct 22 13:51:51 CEST 2015"
with SimpleDateFormat, but I'm not able to find the correct pattern.
Here is what I've tried
String date = "Thu Oct 22 13:51:51 CEST 2015";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("E M d H:m:s z y");
d1 = dateFormat.parse(date);
} catch (ParseException e1) {
Log.e(null, String.valueOf(e1));
}
I get back the error:
java.text.ParseException: Unparseable date: "Thu Oct 22 13:51:51 CEST 2015" (at offset 0)
UPDATE
I tried the solution below by durron597 adapting it to my needs:
String date = "Thu Oct 22 13:51:51 CEST 2015";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy", Locale.US);
Date d1 = dateFormat.parse(date);
} catch (ParseException e1) {
Log.e("null", String.valueOf(e1));
}
but in the logcat I keep getting the error:
java.text.ParseException: Unparseable date: "Thu Oct 22 13:51:51 CEST 2015" (at offset 20)
Use more letters for the longer versions of the Date elements.
In particular the problem in your case was probably the Month portion, which you can see from this part of the Javadoc for SimpleDateFormat:
Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.
You only had one character for Month, it tried to interpet it as a number, found a letter, and failed.
You also need to specify the US locale, as these are United States dates.
Specify the Locale to use in translating the name of the day of the week, “Thu”. You are in Italy (it says so in your profile); when I use Locale.Italy on my machine, I get the same error as you do. If you specify Locale.US as in the below code, it should work.
Update: Android doesn't support three letter time zones, according to this:
Other than the special cases "UTC" and "GMT" (which are synonymous in this context, both corresponding to UTC), Android does not support the deprecated three-letter time zone IDs used in Java 1.1.
You should be able to replace your Europe time zone with the full name of the time zone defined in the official “tz” time zone database (formerly known as Olson database). For example, Europe/Rome instead of "CEST".
Try this instead:
SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy", Locale.US);
date.replace("CEST", "Europe/Rome");
Date d1 = dateFormat.parse(date);
Here's a full working example:
public class DateExample {
public static void main(String[] args) {
String date = "Thu Oct 22 13:51:51 CEST 2015";
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss zzzz yyyy", Locale.US);
date.replace("CEST", "Europe/Rome");
Date d1 = dateFormat.parse(date);
System.out.println(d1);
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
Output:
Thu Oct 22 06:51:51 CDT 2015

Convert UTC Date to local Date

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());

Java. Cant parse date using DateFormat

I have a date string:
Thu Feb 20 08:00:00 EET 1992
And using this code to format it:
String datePatternFrom = "EEE MMM dd HH:mm:ss ZZZ yyyy";
String datePatternTo = "MMM dd, yyyy";
String prettyDate = "";
try {
DateFormat fromFormatter = new SimpleDateFormat(datePatternFrom);
Date date = (Date)fromFormatter.parse(userBirthday.toString());
DateFormat toFormatter = new SimpleDateFormat(datePatternTo);
prettyDate = toFormatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
Why I'am getting the exception?
java.text.ParseException: Unparseable date: "Thu Feb 20 08:00:00 EET 1992" (at offset 0)
The problem is with the weekday and month and your locale.
Thu is English, so you have to tell the parser that it should use English weekdays:
DateFormat fromFormatter = new SimpleDateFormat(datePatternFrom, Locale.US);
This will work for your pattern.
If you do not specify a locale, the default will be used, which is not always an English one. ;-)
It could be your locale. Try making a SDF with datePatternFrom, give it a date to format and print that somewhere. See what pops up.
Probably your userBirthday object was not created as a java.util.Date object. Can you try a System.out.println(userBirthday.getClass().getName());?

Categories