如何在Java中的其他TimeZone中获取当前时间? [英] How do I get the current time in a different TimeZone in Java?

查看:565
本文介绍了如何在Java中的其他TimeZone中获取当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的-我问这样一个基本问题真是愚蠢,但是,嘿.

OK - I feel pretty dumb asking such a basic question, but hey.

我正在尝试获取Java Webapp中不同时区的当前时间.我尝试了以下显而易见的解决方案:在我的servlet中,

I'm trying to get the current time in a different timezone in a Java webapp. I've tried the following obvious solution: in my servlet,

Calendar localCalendar = Calendar.getInstance(myBean.getTimeZone());

然后我将日历对象作为请求属性'localCalendar'传递给JSP:

then I pass the calendar object through to a JSP as a request attribute 'localCalendar':

It is now: [${requestScope.localCalendar.time}]
in TimeZone ${requestScope.localCalendar.timeZone.ID}

但是我的输出似乎忽略了设置的时区,即

but my output seems to ignore the timezone set, i.e.

It is now: [Thu Nov 26 10:01:03 GMT 2009] in TimeZone Indian/Mahe

我猜这与语言环境设置有关,有什么办法可以在另一个时区中获取我的语言环境的时间格式吗?

I'm guessing it's something to do with Locale settings, is there any way to just get the time formatted for my Locale, in another timezone?

推荐答案

Calendar的内部数据基本上是:

The internal data of Calendar is basically:

时间点可以用毫秒值表示,该值是从格林尼治标准时间1970年1月1日00:00:00.000(格里高里安)开始的偏移量.

An instant in time can be represented by a millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

因此,它拥有一个long,无论您对其执行什么操作,它都将是相同的,并且toString不作任何保证.

So, it holds a long that will be the same no matter what operations you use on it and toString makes no promises.

您要根据语言环境和时区设置日期格式.您可以使用 JSTL ,或者您可以使用

You want to format the date as per locale and timezone. You can do this in the presentation layer (the JSP) using things like JSTL or you can format the date in your bean using a DateFormat and return the value as a string.

这篇关于如何在Java中的其他TimeZone中获取当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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