我有一个格式为 yyyy-MM-dd hh:mm a 的字符串
我可以单独获取时区对象,其中上面的字符串代表日期。
我想将其转换为以下格式。
yyyy-MM-dd HH:mm:ss Z
我怎样才能做到这一点?
您可以使用简单日期格式 http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html with yyyy-MM-dd HH:mm:ss
并明确设置TimeZone http://download.oracle.com/javase/6/docs/api/java/util/TimeZone.html:
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"))));
}
打印出:
2010-11-17 13:12:00 +0100
2010-11-17 20:12:00 +0100
2010年12月1日更新:如果要显式打印特殊的 TimeZone,请在 SimpleDateFormat 中设置:
sdf.setTimeZone(TimeZone .getTimeZone("IST"));
System.out.println(sdf.format(getSomeDate(
"2010-11-17 01:12 pm", TimeZone.getTimeZone("IST"))));
哪个打印2010-11-17 13:12:00 +0530
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)