IST到EST时间转换在Java中

我在IST Time中有一个Java日期字段。 我想将相同的转换为EST时间,输出应仅作为日期类型。 我可以使用下面的代码完成相同的工作: –

SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta")); Date date = new Date(); DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); timeFormat.setTimeZone(TimeZone.getTimeZone("America/New_York")); String estTime = timeFormat.format(date); date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse(estTime); 

上面这段代码的问题在于虽然日期是在EST时间内转换的,但时区仍然显示为IST而不是EST。 剩下的日期转换得很好。 有没有办法在日期字段中明确设置时区为EST。有关此的任何帮助将非常感谢。

-Subhadeep

Date类与时区无关。 基本上,它总是基于GMT,虽然在打印时它使用当前系统时区来调整它。

但是, Calendar是特定于时区的。 请参见Calendar.setTimeZone() 。

考虑:

  Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("America/New_York")); cal.setTime(new Date()); 

你应该在SimpleDateFormat模式中为时区模式添加z吗?

因此,它应该是DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z") 。 我改变了你的代码:

 public static void main(String[] args) throws ParseException { SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); dateTimeFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta")); Date date = new Date(); System.out.println(dateTimeFormat.format(date)); // this print IST Timezone DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); timeFormat.setTimeZone(TimeZone.getTimeZone("America/New_York")); String estTime = timeFormat.format(date); date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z", Locale.ENGLISH).parse(estTime); System.out.println(timeFormat.format(date)); // this print EDT Timezone currently (on March) } 

在上一个打印语句中,当前日期格式使用EDT时区 (东部夏令时)打印。 也许是因为这个 。

John B的正确答案解释说java.util.Date似乎有一个时区但没有。 它的toString方法在生成字符串表示时应用JVM的默认时区。

这是避免与Java捆绑的java.util.Date和.Calendar类的众多原因之一。 避免他们。 而是使用Joda-Time或Java 8中内置的java.time包(受Joda-Time启发,由JSR 310定义)。

以下是Joda-Time 2.3中的一些示例代码。

 String input = "01/02/2014 12:34:56"; DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm:ss" ); DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" ); DateTime dateTimeIndia = formatterInput.withZone( timeZoneIndia ).parseDateTime( input ); DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" ); DateTime dateTimeNewYork = dateTimeIndia.withZone( timeZoneNewYork ); DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC ); 

转储到控制台……

 System.out.println( "input: " + input ); System.out.println( "dateTimeIndia: " + dateTimeIndia ); System.out.println( "dateTimeNewYork: " + dateTimeNewYork ); System.out.println( "dateTimeUtc: " + dateTimeUtc ); 

跑的时候……

 input: 01/02/2014 12:34:56 dateTimeIndia: 2014-01-02T12:34:56.000+05:30 dateTimeNewYork: 2014-01-02T02:04:56.000-05:00 dateTimeUtc: 2014-01-02T07:04:56.000Z