简体   繁体   中英

How to convert the date String with timezone

I have some string with date format such as

Sat Aug 15 13:53:41 MYT 2015

I use SimpleDateFormate and tried to convert the String type into Date type. It converted the String type into Date type, however, the timezone "MYT" is not recognized by Java and instead it was set to the default timezone of my computer ie "CST". I need the time zone to be record in the Date object. How could I do it?

If you know the time zone in advance, you can hardcode it into the formatter like this:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Asia/Kuala_Lumpur"));
Date date = format.parse("2016-01-01 00:00:00 MYT");

You can follow the code

String dateStr = "Sat Aug 15 13:53:41 MYT 2015";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);        

Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" +         cal.get(Calendar.YEAR);

System.out.println("formatedDate : " + formatedDate); 

Resource Link:

  1. How to convert “ Mon Jun 18 00:00:00 IST 2012” to 18/06/2012?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM