Java – converts a string to a date using a time zone
•
Java
I have a string pattern yyyy MM DD HH: mm a
I want to convert it to the following format yyyy-MM-dd HH:mm:ss Z
What should I do?
Solution
You can use simpledateformat with yyyy MM DD HH: mm: SS and explicitly set timezone:
public static Date getSomeDate(final String str,final TimeZone tz) throws ParseException { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm a"); sdf.setTimeZone(tz); return sdf.parse(str); } /** * @param args * @throws IOException * @throws InterruptedException * @throws ParseException */ public static void main(final String[] args) throws ParseException { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); System.out.println(sdf.format(getSomeDate( "2010-11-17 01:12 pm",TimeZone.getTimeZone("Europe/Berlin")))); System.out.println(sdf.format(getSomeDate( "2010-11-17 01:12 pm",TimeZone.getTimeZone("America/Chicago")))); }
Print out
Update 2010-12-01: if you want to explicitly print a special timezone, please set it in simpledateformat:
sdf.setTimeZone(TimeZone .getTimeZone("IST")); System.out.println(sdf.format(getSomeDate( "2010-11-17 01:12 pm",TimeZone.getTimeZone("IST"))));
Which print? 2010-11-17 13:12:00 0530
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码