Reputation: 573
Upvotes: 1
Views: 1810
Reputation: 428
You can create Utility (Generic methods) to convert date with timezone below some example to convert.
public static Date buildUTCDate(String dateString) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat(SecureCareConstant.SQL_TIMESTAMP_FORMAT);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.parse(dateString);
}
public static String dateToString(Date date) {
return new SimpleDateFormat(SecureCareConstant.SQL_TIMESTAMP_FORMAT).format(date);
}
public static Date buildUTCDate(Date date) {
SimpleDateFormat fromDateFormat = new SimpleDateFormat(SecureCareConstant.SQL_TIMESTAMP_FORMAT);
SimpleDateFormat toDateFormat = new SimpleDateFormat(SecureCareConstant.SQL_TIMESTAMP_FORMAT);
toDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateString = new SimpleDateFormat(SecureCareConstant.SQL_TIMESTAMP_FORMAT).format(date);
try {
return fromDateFormat.parse(toDateFormat.format(fromDateFormat.parse(dateString)));
} catch (ParseException e) {
LOGGER.error("ParseException in buildUTCDate()", e);
}
return null;
}
public static Date getCurrentTimeZoneDate(final Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
TimeZone z = c.getTimeZone();
int offset = z.getRawOffset();
if (z.inDaylightTime(new Date())) {
offset = offset + z.getDSTSavings();
}
int offsetHrs = offset / 1000 / 60 / 60;
int offsetMins = offset / 1000 / 60 % 60;
c.add(Calendar.HOUR_OF_DAY, (+offsetHrs));
c.add(Calendar.MINUTE, (+offsetMins));
return c.getTime();
}
public static String toLocalTime(Date dateUTC) {
if (dateUTC == null) {
return StringUtils.EMPTY;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(SecureCareConstant.WEB_SERVICE_DATE_FORMAT);
return dateFormat.format(new Date(dateUTC.getTime() + TimeZone.getDefault().getOffset(dateUTC.getTime())));
}
Upvotes: 0
Reputation: 123
There are already several threads regarding the best practices with datetime, e.g. Daylight saving time and time zone best practices
I would suggest the following:
From my experience it's best to let the client handle all local datetime/zone conversions and commit onto using UTC for all communication and backend usecases.
If you want to dump the date directly into a webpage you can use a js-library like http://momentjs.com/ to convert it to a locale datetime.
Upvotes: 3