Hi,
I know this is weird requirement but I'm stuck and I need some kind of solution. I'm using Java 1.5 and it's not possible to switch to another version even if solution is available.
Datetime is received in string from source system and need to convert it into java.util.Date object before storing it in DB.
I'm using SimpleDateFormat to convert string to date, basically using parser. Problem is when DST comes into effect. Underlying API adds 1 hour which is incorrect as per requirement.
-----
Example: Input Date - 20100328010000 (23 ^rd^ March 2010 01:00:00). When parsed I get date as 23 ^rd^ March 2010 *02*:00:00.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class DateTimeTest {
public static final String convertDate(String inputDate, String inputDateFormat, String inputTimeZone, String outputDateFormat, String reqTimeZone) {
String outputDate = null;
DateFormat dateFormat = null;
try {
// Set input date format
dateFormat = new SimpleDateFormat(inputDateFormat);
// Set input date time zone
dateFormat.setTimeZone(TimeZone.getTimeZone(inputTimeZone));
// Parse date
Date date = dateFormat.parse(inputDate);
// Set output date format
dateFormat = new SimpleDateFormat(outputDateFormat);
// Set output date time zone
dateFormat.setTimeZone(TimeZone.getTimeZone(reqTimeZone));
// Format output date
outputDate = dateFormat.format(date);
}
catch (ParseException e) {
System.err.println(e);
}
return outputDate;
}
public static final Date convertDate(String inputDate, String inputDateFormat, String inputTimeZone) {
DateFormat dateFormat = null;
try {
// Set input date format
dateFormat = new SimpleDateFormat(inputDateFormat);
// Set input date time zone
dateFormat.setTimeZone(TimeZone.getTimeZone(inputTimeZone));
// Parse date
return dateFormat.parse(inputDate);
}
catch (ParseException e) {
System.err.println(e);
}
return null;
}
public static void main(String[] args) throws Exception {
String inputDate = "20100328010000";
Date date = DateTimeTest.convertDate(inputDate, "yyyyMMddHHmmss", "GMT");
System.out.println("1 : " + date);
String dateString = DateTimeTest.convertDate(inputDate, "yyyyMMddHHmmss", "GMT", "yyyy-MM-dd HH:mm:ss", "GMT");
System.out.println("2 : " + dateString);
}
}
Output
1 : Sun Mar 28 02:00:00 BST 2010 // Incorrect
2 : 2010-03-28 01:00:00 // Correct but String
-----
How can this be resolved? I have exhausted all possible solutions I knew of.
Using GTM as both input and output TimeZone, I'll get correct date but requirement in date object not String. Even if I want to I can't make changes in existing code.