在Java中使用各种日历TimeZone(不使用Joda时间) [英] Working with various Calendar TimeZone in Java (without using Joda Time)

查看:208
本文介绍了在Java中使用各种日历TimeZone(不使用Joda时间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种方法,可以根据用户输入获取各个时区的当前时间。我知道我可以使用 Joda时间!但是这是唯一的方法吗?

I was looking for a way to get current time in various timezones based on an user input. I know I could use Joda Time! but is that the only way?

在Java中没有这样的选项吗?我尝试了下面的代码,为所有3个sysouts提供相同的输出。

Isn't there an option in Java for doing this? I tried the following code which gives the same output for all 3 sysouts.

Calendar pst = Calendar.getInstance(TimeZone.getTimeZone("PST"));
System.out.println("PST " + pst.getTime());
Calendar ist = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println("IST " + ist.getTime());
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("Etc/UTC"));
System.out.println("UCT " + utc.getTime());

我在这里错过了其他时区的当前时间?

What am I missing here to get current time in other timezones?

推荐答案

是的,在每种情况下(或相隔几毫秒)显示相同的值,因为三个日历都指向同一个 em>(尽管执行时间),这是一个 java.util.Date 表示。这是 Calendar.getTime()的结果。

Yes, that would show the same value in every case (or milliseconds apart) because the three calendars all refer to the same instant in time (execution time notwithstanding) and that's all that a java.util.Date represents. That's the result of Calendar.getTime().

然而, code>本身 知道时区,当使用 Calendar.get 等时会反映出来。当您使用 SimpleDateFormat ,您可以指定特定时区。

However, the Calendar itself does know about time zones, and that will be reflected when you use Calendar.get etc. It will also be used when you use a SimpleDateFormat, where you can specify a particular time zone.

// Specify whatever format you want - bear in mind different locales etc
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(calendar.getTimeZone());
String text = format.format(calendar.getTime());

这不清楚你想要做什么,但基本上你需要知道类型是时区感知,而哪些不是。非常重要的是要了解 java.util.Date 没有格式,日历系统或时区: 自Unix纪元以来的毫秒数。

It's not clear exactly what you're trying to do, but basically you need to be aware of which types are time zone aware, and which aren't. It's really important to understand that a java.util.Date doesn't have a format, a calendar system or a time zone: it's just the number of milliseconds since the Unix epoch.

这篇关于在Java中使用各种日历TimeZone(不使用Joda时间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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