将字符串转换为带时区的日期 [英] Converting string to date with timezone

查看:275
本文介绍了将字符串转换为带时区的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串模式yyyy-MM-dd hh:mm a
,我可以分别获取时区对象,其中上述字符串表示日期。

I have a string in the pattern yyyy-MM-dd hh:mm a and i can get the time zone object separately in which the above string represents the date.

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

I want to convert this to the below format. yyyy-MM-dd HH:mm:ss Z

我该怎么办?

推荐答案

您可以使用 SimpleDateFormat yyyy-MM-dd HH:mm:ss 并显式设置 TimeZone

You can use SimpleDateFormat with yyyy-MM-dd HH:mm:ss and explicitly set the 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 13:12:00 +0100

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

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

更新2010-12-01:
如果要明确打印特殊的时区,请设置它在SimpleDateFormat中:

Update 2010-12-01: If you want to explicitly printout a special TimeZone, set it in the 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

这篇关于将字符串转换为带时区的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆