The class Date/Timestamp
represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.
Date/Timestamp
doesn't know about the given time is on which timezone.
If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.
If you try to print a Date/Timestamp object using toString()
, it will convert and print the time with the default timezone of your machine.
So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)
To conclude Date.getTime()
will give UTC time, but toString()
is on locale specific timezone, not UTC.
The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
dateFormatLocal.setTimeZone(timeZone);
java.util.Date parsedDate = dateFormatLocal.parse(date);
Use dateFormat.format
for taking input Date (which is always UTC), timezone and return date as String.
If you print the parsedDate
object, the time will be in default timezone.
But you can store the UTC time in DB like below.
Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
if (tsSchedStartTime != null) {
stmt.setTimestamp(11, tsSchedStartTime, calGMT );
} else {
stmt.setNull(11, java.sql.Types.DATE);
}