I want to convert a PST Time which is in format of MM/dd/yyyy HH:mm
to MST Time.
Code which i tried is below. Currently i am in IST Time Zone
and using JDK1.7
.
The below code produces the Output This is the Code Test : 08/31/2015 07:20 MST
I have a doubt whether it is really a MST or not! because the MST Time here shows me as 20:50
so i taught, it should either display as 8:50
considering the am/pm (12hr) clock.
This is what confused me-I want to know what went wrong?
/**
*
* Read a Date in the Format of MM/dd/yyyy HH:mm which is a (PST) Time Zone.
* Convert it to MST Time Zone and Save.
*
* Step 1 : Set Timezone as PST to Date in format of MM/dd/yyyy HH:mm,
* Step 2 : Convert PST to MST Time,
* Step 3 : Convert MST Time to Date in format of MM/dd/yyyy HH:mm.
*
* Eg: PST Time Now -> 08/31/2015 19:50;
* MST Time Now -> 08/31/2015 20:50;
*
*
*/
package dates;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DateUtilities {
public static void main(String[] args) {
String dateInString = "08/31/2015 19:50";
System.out.println("This is the Code Test"+MstTimeNow(step1(StringToDate(dateInString))));
// step2(step1(StringToDate(dateInString)));
}
// String To Date
public static Date StringToDate(String dateInString) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
date = sdf.parse(dateInString);
// System.out.println("String To Date "+date);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
// To Set TimeZone as PST
public static Calendar step1(Date date) {
Calendar cal = Calendar.getInstance();
TimeZone tz = TimeZone.getTimeZone("PST");
cal.setTimeZone(tz);
cal.setTime(date);
// System.out.println("Get Calendar PST Time: "+cal.getTime() +" TimeZone "+cal.getTimeZone());
return cal;
}
// Calendar To MST Time
public static String MstTimeNow(Calendar cal) {
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm z");
formatter.setCalendar(cal);
formatter.setTimeZone(TimeZone.getTimeZone("MST"));
String mstTimeString = formatter.format(cal.getTime());
// System.out.println("MST time Now is : "+mstTimeString);
return mstTimeString;
}
}
Solution given by assylias produces an output below which is what expected!
Input String : 08/31/2015 19:50
Local Date Time: 2015-08-31T19:50
Zoned Date Time PST: 2015-08-31T19:50-07:00[America/Los_Angeles]
Zoned Date Time MST: 2015-08-31T20:50-06:00[America/Denver]