如何在Java中获取时区的当前日期和时间?

Ser*_*Amo 49 java timezone jodatime

我的应用程序托管在伦敦服务器中.我在西班牙马德里.所以时区是-2小时.

如何获取我的时区的当前日期/时间.

Date curr_date = new Date(System.currentTimeMillis());
Run Code Online (Sandbox Code Playgroud)

例如

Date curr_date = new Date(System.currentTimeMillis("MAD_TIMEZONE"));
Run Code Online (Sandbox Code Playgroud)

随着Joda-Time

DateTimeZone zone = DateTimeZone.forID("Europe/Madrid");
DateTime dt = new DateTime(zone);
int day = dt.getDayOfMonth();
int year = dt.getYear();
int month = dt.getMonthOfYear();
int hours = dt.getHourOfDay();
int minutes = dt.getMinuteOfHour();
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 89

Date始终基于UTC ...或时区中立的,这取决于你想如何看待它.甲Date 表示在一个时间点; 它独立于时区,自Unix时代以来只有几毫秒.没有"本地实例"的概念Date.使用Date结合Calendar和/或TimeZone.getDefault()使用"本地"时区.使用TimeZone.getTimeZone("Europe/Madrid")得到马德里时区.

...或者使用Joda Time,它可以让整个事情变得更加清晰,IMO.在Joda Time中,您将使用一个DateTime值,该值是特定日历系统和时区中的即时时间.

在Java 8中你使用的java.time.ZonedDateTime是Joda Time的Java 8等价物DateTime.

  • `日期 currentDate = Calendar.getInstance(TimeZone.getDefault()).getTime()` (4认同)
  • @ user3132194:你认为对新的Date()有什么好处? (2认同)
  • @ user3132194:复制和粘贴这是一个非常糟糕的*模板."new Date()"没有任何好处.如果您想要当地时间,则不应使用"日期".如果你认为你的代码对'new Date()`做了一些有用的事情,我怀疑你误会了. (2认同)

Jes*_*per 52

正如Jon Skeet所说,java.util.Date没有时区.一个Date对象表示自1970年1月1日,上午12:00,UTC毫秒数.它不包含时区信息.

将Date对象格式化为字符串时(例如使用)SimpleDateFormat,可以在DateFormat对象上设置时区,以便知道要在哪个时区显示日期和时间:

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

System.out.println("Date and time in Madrid: " + df.format(date));
Run Code Online (Sandbox Code Playgroud)

如果您想要运行程序的计算机的本地时区,请使用:

df.setTimeZone(TimeZone.getDefault());
Run Code Online (Sandbox Code Playgroud)


dfa*_*dfa 16

使用日历很简单:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid"));
Date currentDate = calendar.getTime();
Run Code Online (Sandbox Code Playgroud)

  • 常见问题是正确的.如果有人谷歌**任何**编程问题,我们希望Stack Overflow成为最佳搜索结果(或非常接近它).这意味着即使是最微不足道的问题,如果SO上还没有,那就是公平的游戏. (15认同)
  • 请阅读http://stackoverflow.com/faq上的stackoverflow常见问题解答:"没有问题太琐碎或太"新手".哦,是的,它应该是关于编程的." (11认同)
  • 即使您为日历实例设置了时区,也不会考虑使用`getTime()`方法.从它的javadocs:`返回一个Date对象,表示这个Calendar的时间值(与Epoch的毫秒偏移量). (4认同)
  • “GMT-2”是否会给出“始终 GMT-2”区域,其中不包括夏令时? (2认同)

Zee*_*han 9

使用Java 8和更高版本中内置的java.time类:

public static void main(String[] args) {
        LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(localNow);
        // Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
        ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(zoneNow);
        // Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
    }
Run Code Online (Sandbox Code Playgroud)