java – 使用时区将字符串转换为日期

我有一个字符串的模式yyyy-MM-dd hh:mm a
我可以分别得到上述字符串代表日期的时区对象.

我想将其转换为以下格式.
yyyy-MM-dd HH:mm:ss Z

我该怎么办?

解决方法

您可以使用 SimpleDateFormat与yyyy-MM-dd HH:mm:ss并显式设置 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"))));
}

打印出来

2010-11-17 13:12:00 +0100

2010-11-17 20:12:00 +0100

更新2010-12-01:
如果要明确打印一个特殊的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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...