The web server is in New York. The users can be anywhere in the country. The users get to select the current location that they are working for (not necessariliy be their current physical location). For example, they can physically be in Texas, but they want to select California as their current location. And the system must display current California time to them.
I wrote a method to calculate the local datetime based on a given GMT offset. Since the users will select their current location, we know the GMT offset. For example, if they selected California, we know the GMT offset is -8. The codes are as follow:
private void setCurrentGmtDatetime(String idfGmtOffsetStr) {
int idfGmtOffset = 0;
long newDatetimeInMillis = new Date().getTime();
long gmtDatetimeInMillis = (new Date().getTime()) -
(TimeZone.getDefault().getOffset(new Date().getTime()));
Date newDatetime = null;
try {
idfGmtOffset = Integer.parseInt(idfGmtOffsetStr);
newDatetimeInMillis = gmtDatetimeInMillis + (idfGmtOffset * 3600000);
newDatetime = new Date(newDatetimeInMillis);
} catch (NumberFormatException nfex) {
nfex.printStackTrace();
System.err.println("Invalid offset string. Use Current Date");
newDatetime = new Date();
}
// a bunch of setters here...
}
Everything works until Daylight Saving Time came into the picture. Therefore, I modified the line to adjust the time according to the Daylight Saving Time:
long gmtDatetimeInMillis = (new Date().getTime()) -
((TimeZone.getDefault().getOffset(new Date().getTime())) -
TimeZone.getDefault().getDSTSavings());
Do you guys think this is good enough? I know the answer already, but I think this is an interesting topic to talk about. So, I think of sharing this with you all.