Parsing time stamp strings from a different time zone - java

I have a String with timestamp in GMT. I want to convert this to a DateTime object in EST.
E.g If the string has:
final String gmtTime = "20140917-18:55:25"; // 4:55 PM GMT
I need to convert this to : 20140917-12:55:25 //12:55 PM EST
All these tries failed:
System.out.println("Time in GMT " + DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").parseDateTime(gmtTime));
System.out.println("Time in EST " +
DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").parseDateTime(gmtTime).withZone(DateTimeZone.forID("America/New_York")));
Output:
Time in GMT 2014-09-17T18:55:25.000-04:00
Time in EST 2014-09-17T18:55:25.000-04:00 //I expect: 2014-09-17T12:55:25.000-04:00
Any suggestions?

Joda-Time
Here a Joda-Time 2.4 solution:
String gmtTime = "20140917-18:55:25";
DateTime dateTimeGMT =
DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").withZoneUTC().parseDateTime(gmtTime);
System.out.println("Time in GMT " + dateTimeGMT); // Time in GMT 2014-09-17T18:55:25.000Z
System.out.println(
"Time in EST "
+ DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").withZone(
DateTimeZone.forID("America/New_York")
).print(dateTimeGMT)
); //Time in EST 20140917-14:55:25
I think that you have the wrong expectation regarding the result. EST (more correct to use is "America/New_York" as zone identifier) is four hours behind UTC, hence the local timestamp there is four hours earlier than the local representation of the same moment at UTC-offset.
Also note that I set the timezone on the formatter not on the parsed DateTime-object.

#Test
public void TimeZoneTest() {
Date now = new Date();
String DATE_PATTERN = "yyyyMMdd-HH:mm:ss";
DateFormat dfEST = new SimpleDateFormat(DATE_PATTERN);
dfEST.setTimeZone(TimeZone.getTimeZone("America/New_York"));
DateFormat dfGMT = new SimpleDateFormat(DATE_PATTERN);
dfGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dfEST.format(now));
System.out.println(dfGMT.format(now));
}
And the output is:
20140919-09:02:19
20140919-13:02:19

Related

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 date string parse creates difference of timezone

I am bit frustrated by this.
I have a String "2015-02-18T23:44:59" which represents time in GMT format.
I want to parse this date into date object.
String dateStr = "2015-02-18T23:44:59";
Date date = DateUtils.parseDate(dateStr, new String[]{"yyyy-MM-dd'T'HH:mm:ss"});
System.out.println(dateStr + " \t" + date.toString());
This outputs :
2015-02-18T23:44:59 Thu Feb 19 05:14:59 IST 2015
As you can see latter time has time zone IST but my original time was GMT.
I don't think there is any parse function which takes current date's time zone.
One way to answer is this question is that :
date.setTime(date.getTime() + ( date.getTimezoneOffset() * 60 * 1000));
System.out.println("\t" + date.toString());
This outputs:
Wed Feb 18 23:44:59 IST 2015
Which seems correct time (but incorrect time zone). Additionally, getTimezoneOffset() is deprecated.
Can anyone suggest me a better way to deal with String dates considering time zones.
I'd use a date format:
SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = utcFormat.parse("2015-02-18T23:44:59");

Simple date format in IST and KST

I use the following simple date format to parse a string,
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
String time = "Wed Mar 06 21:00:00 IST 2014";
Date date = dateFormat.parse(time);
This throws no error whreas,
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
String time = "Wed Mar 06 21:00:00 KST 2014";
Date date = dateFormat.parse(time);
Throws unparseable date exception.
where,
IST - Indian standard time
*KST - korean standard time*
I have decided to remove time zone because of the exception.
Is there any other way to work around this issue?
Please help
Avoid Time Zone Codes
Avoid those 3 or 4 letter codes for time zones. They are neither standardized nor unique. For example, the IST you cite as "Indian Standard Time" is also "Irish Standard Time". Plus they are confusing when in fact you may mean "Summer Time"/"Daylight Saving Time". Instead use proper time zone names, usually made up of a country plus primary city.
Use Sensible Formats For Date-Time Strings
That format "Wed Mar Thu 21:00:00 IST 2014" is not good. Besides being wrong (looks like you typed "Wed" or "Thu" where you should have a day-of-month number), it uses the 3-4 letter code, contains superfluous data (day of week), and assumes English readers. When moving date-time values around as text, use the sensible ISO 8601 format: YYYY-MM-DDTHH:MM:SS.sssZ such as 2014-03-04T23:20:28Z.
If changing that format is out of your control, you'll have to determine all the possible 3-4 letter codes that may be used in your data sets and see if your date-time library can handle them.
Avoid java.util.Date/Calendar
The java.util.Date and .Calendar classes are notoriously troublesome. They are outmoded as of Java 8 with the new java.time package. That package is based on the Joda-Time library. Use either Joda-Time or java.time.
Joda-Time
Note that in contrast to java.util.Date, a Joda-Time DateTime object truly knows its assigned time zone.
Here's some Joda-Time 2.3 example code.
String inputIso = "2014-03-19T21:00:00+05:30";
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( inputIso, timeZoneIndia );
// Adjust to Korea Time.
DateTimeZone timeZoneKorea = DateTimeZone.forID( "Asia/Seoul" );
DateTime dateTimeKorea = dateTimeIndia.withZone( timeZoneKorea );
// Adjust to UTC (GMT).
DateTime dateTimeUtc = dateTimeKorea.withZone( DateTimeZone.UTC );
String inputLame = "Thu Mar 20 21:00:00 KST 2014";
DateTimeZone timeZone = null;
if( inputLame.contains( "IST" )) { // Assume IST = India time.
timeZone = DateTimeZone.forID( "Asia/India" );
inputLame = inputLame.replace( " IST ", " ");
}
if( inputLame.contains( "KST" )) { // Assume KST = Korea time.
timeZone = DateTimeZone.forID( "Asia/Seoul" );
inputLame = inputLame.replace( " KST ", " ");
}
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss yyyy" ).withZone( timeZone ).withLocale( java.util.Locale.ENGLISH );
DateTime dateTimeLame = formatter.parseDateTime( inputLame );
Dump to console…
System.out.println( "dateTimeIndia: " + dateTimeIndia );
System.out.println( "dateTimeKorea: " + dateTimeKorea );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeLame: " + dateTimeLame );
When run…
dateTimeIndia: 2014-03-19T21:00:00.000+05:30
dateTimeKorea: 2014-03-20T00:30:00.000+09:00
dateTimeUtc: 2014-03-19T15:30:00.000Z
dateTimeLame: 2014-03-20T21:00:00.000+09:00
Both the dates are invalid, hence both would throw the error:
String time = "Wed Mar Thu 21:00:00 IST 2014";
Thu is invalid as the day of the week is already consumed by EEE - Wed combination. You need to set a day of the month there.
Try parsing the following date, it should work for your case:
String time = "Wed Mar 12 21:00:00 KST 2014";
Try this piece of code and see if KST is a valid time zone id
String[] timezoneIdArr = TimeZone.getAvailableIDs();
for (String tzId : timezoneIdArr) {
System.out.println(tzId);
}
If not, then enter zone id like "Asia/Seoul" or something. That should work.
Please note that I have not tried it. Please check exact spellings of the time zones.
Update:
Try the code below. See what KST yields. Uncomment and try with Asia/Seoul. For your reference, uncomment and see how PST works.
private static void calTest() {
String zone = "KST";
//String zone = "Asia/Seoul";
//String zone = "PST";
long millis = System.currentTimeMillis();
//get calendar of Korea time zone.
Calendar kst = Calendar.getInstance(TimeZone.getTimeZone(zone));
//set its time to a UTC millisecond value. probably redundant, but just to demonstrate
kst.setTimeInMillis(millis);
String formattedKst = formatTime(kst);
System.out.println(" Original - " + formattedKst);
//now we convert the formatted string back to a Calendar .
Calendar parsedKst = parseTime(formattedKst, zone);
System.out.println(" Parsed - ");
System.out.println("" + parsedKst.get(Calendar.YEAR) + "-"
+ (parsedKst.get(Calendar.MONTH) + 1) + "-"
+ parsedKst.get(Calendar.DATE) + " "
+ parsedKst.get(Calendar.HOUR_OF_DAY) + ":"
+ parsedKst.get(Calendar.MINUTE) + ":"
+ parsedKst.get(Calendar.SECOND) + "."
+ parsedKst.get(Calendar.MILLISECOND) + " "
+ parsedKst.getTimeZone().getID() + " "
+ parsedKst.getTimeZone().getDisplayName() + " "
);
}
private static Calendar parseTime(String formattedDateTime, String ID) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX zzz");
sdf.setTimeZone(TimeZone.getTimeZone(ID));
sdf.setLenient(false);
try {
sdf.parse(formattedDateTime);
} catch (ParseException e) {
e.printStackTrace();
}
return sdf.getCalendar();
}
private static String formatTime(Calendar cal) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX zzz");
sdf.setCalendar(cal);
return sdf.format(cal.getTime());
}

simpledateformat parse not parsing date properly

i am trying to print the date as : 2013/11/20 08 30 but it is printing as below after parsing the date through simpledateformat Wed Nov 20 14:00:00 IST 2013,
here i passed the HH and MM as 08 30 but after parsing it changed to 14:00:00
Can you please suggest
public class PrintDate {
public static void main(String[] args) {
System.out.println(getDate("2013/11/20","08","30"));
}
public static Date getDate(String date, String hour, String miniute) {
final SimpleDateFormat displayDateTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH mm");
displayDateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String paddedHour = hour.length() == 2 ? hour : "0" + hour;
int min = Integer.valueOf(miniute);
int remainder = min % 5;
int roundMinute = remainder > 2 ? min - remainder + 5 : min - remainder;
String minuteStr = String.valueOf(roundMinute);
String paddedMinuteStr = minuteStr.length() == 2 ? minuteStr : "0" + minuteStr;
String startDateStr = date + " " + paddedHour.toUpperCase() + " " + paddedMinuteStr;
Date startDate = null;
try {
startDate = displayDateTimeFormat.parse(startDateStr);
} catch (ParseException e) {
}
return startDate;
}
}
after parsing the date through simpledateformat Wed Nov 20 14:00:00 IST 2013, here i passed the HH and MM as 08 30 but after parsing it changed to 14:00:00
Yes, because you specified that you wanted it to be parsed as a UTC value. However, the Date itself has no concept of a time zone - it's just an instant in time. Date.toString() will always use the default time zone.
2013-11-20 08:30 UTC is the same instant in time as 2013-11-20 14:00 IST, so it's actually parsing it correctly - it's just the result of Date.toString() which is confusing you.
If you want to preserve the time zone as well, you'll have to do that separately - or (better) use Joda Time which is a much nicer date/time API, and has a DateTime class which represents an instant in time in a particular calendar system and time zone.
Just try below lines of code to get date in desired format -
Date date=new Date(2013-1900,10,20,8,30);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyy/MM/dd K mm");
String strFormatDate = dateFormat.format(date);
Date dtFormatDate = dateFormat.parse(strFormatDate);
System.out.println("Formatted date in String:"+strFormatDate);
System.out.println("Formatted Date:"+dtFormatDate);
Just give K instead of HH in date format. You can give date as 14 30 then also this format will convert date as you desired.
Thanks

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.

Categories