Calender.getTime()没有显示给定timeZone的日期时间

时间:2015-10-10 07:53:28

标签: java timezone

我在时间区+05:30,我想要欧洲的时区,所以我正在尝试这个: -

    TimeZone tmz=TimeZone.getTimeZone("Europe/Zurich");
    Calendar calender=new GregorianCalendar(tmz);
    Date date=calender.getTime();
    String datestr=new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(date);
    System.out.println(datestr+" CST");

但我得到的是时区的时间

4 个答案:

答案 0 :(得分:1)

您需要在SimpleDateFormat 中设置时区Date值没有时区,因此您的初始代码毫无意义 - 您只需拨打new Date()

请注意,您的格式字符串也不正确 - 您使用的是分钟而不是几个月,并且您使用的是12小时制,几乎肯定不是您想要的。

我怀疑你的代码应该是:

TimeZone tmz = TimeZone.getTimeZone("Europe/Zurich");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
format.setTimeZone(tmz);
String datestr = format.format(new Date());

顺便说一句,如果可能可以,我会避免使用所有这些类 - 如果你遇到Java 7或更早版本,请使用Joda Time,{{1}如果您使用的是Java 8,那么它们就是更好的日期/时间API。

答案 1 :(得分:0)

你可以试试这个.. 要根据您为Calendar设置的时区显示时间,您可以使用DateFormat对象并执行以下操作:

import java.text.DateFormat;
import java.util.*;

public class PrintDate
{
   public static void main (String[] args)
   {
      TimeZone tmz=TimeZone.getTimeZone("Europe/Zurich");

      DateFormat df = DateFormat.getDateTimeInstance();
      df.setTimeZone(tmz);

      System.out.println("Current time in Europe--> " +
                         df.format(Calendar.getInstance(tmz).getTime()));
   }
}

答案 2 :(得分:0)

如果您使用带有新Clock API的Java8,可以使用下面的

获得相同的内容
    ZoneId zone = ZoneId.of("Europe/Zurich");
    LocalTime localTime = LocalTime.now(zone);

DateTimeFormatter有很多格式化日期和时间的选项

修改

    LocalDateTime dateTime = LocalDateTime.now(zoneId);

获取日期和时间,

答案 3 :(得分:0)

answer by Jon Skeet是正确和直接的,应该被接受。

answer by Saravana遵循Skeet建议使用新的java.time框架。但该答案有时间,问题要求日期时间。因此,这里的答案。

java.time

java.time框架与Java 8及更高版本捆绑在一起。见Tutorial。这些新课程的灵感来自Joda-Time,由JSR 310定义,并由ThreeTen-Extra项目进行扩展。对于麻烦的旧类,java.util.Date / .Calendar等,它们是一个巨大的进步。

目前的日期时间很容易获得。指定所需/预期的time zone by name。如果省略,则隐式应用JVM的当前默认时区。

ZoneId zoneId = ZoneId.of ( "Europe/Zurich" );
ZonedDateTime nowZurich = ZonedDateTime.now ( zoneId );

您可以生成该日期时间值的String表示形式。默认情况下,toString方法使用标准ISO 8601格式,但通过在括号中附加区域名称来扩展标准。

String outputStandard = nowZurich.toString (); // ISO 8601 format, extended by appending name of zone in brackets.

或者,您可以使用localized format,甚至define your own format。指定Locale

Locale localeFrenchSwitzerland = new Locale.Builder ().setLanguage ( "fr" ).setRegion ( "CH" ).build ();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL ).withLocale ( localeFrenchSwitzerland );
String outputFrenchSwitzerland = nowZurich.format ( formatter );

转储到控制台。

System.out.println ( "outputStandard: " + outputStandard );
System.out.println ( "outputFrenchSwitzerland: " + outputFrenchSwitzerland );

跑步时。

  

outputStandard:2015-10-11T02:39:58.287 + 02:00 [欧洲/苏黎世]

     

outputFrenchSwitzerland:dimanche,11 octobre 2015 02.39。 h CEST

如果你真的需要java.util.Date来与其他尚未针对java.time更新的类进行互操作,请转换。

java.util.Date date = java.util.Date.from ( nowZurich.toInstant () );