yuva ツ yuva ツ - 1 year ago 53
Java Question

Current time not getting converted into MST timezone

I'm trying to convert current time in MST using below code

DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
TimeZone toTimeZone = TimeZone.getTimeZone("MST");
Date date = new Date();
String strDate = sdf.format(date.getTime());

strDate displaying correct MST time, but after parsing it is giving wrong date time.

Date currentDate = sdf.parse(strDate);

I want current MST time in Date format not in string.

Answer Source

Please check Time Zones and java.util.Date on the Documentation page...

A java.util.Date object does not have a concept of time zone.

  • There is no way to set a timezone for a Date
  • There is no way to change the timezone of a Date object
  • A Date object created with the new Date() default constructor will be initialised with the current time in the system default timezone

All you did is add a time zone information for the formatting part... setTimeZone does not convert anything.