2012-09-17 105 views
1

我使用靛蓝服务发布2.我已经写了下面的代码:如何在不同的时区获取日期和时间?

TimeZone calcutta = TimeZone.getTimeZone("Asia/Calcutta"); 
Date now = new Date(); 
DateFormat format = 
    DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); 
format.setTimeZone(calcutta); 
jlabel_IndiaTime.setText((format.format(now).toString())); 

是表示Monday, September 17,2012 1:13:23 PM IST,但在印度的时间是上午10点14分。我正在尝试从纽约来。任何人都可以帮我吗?

+0

@Nikhil Agrawal:不是C#。我正在用JAVA编写代码。 – sattu

+1

当你打印'Timezone.getDefault()'时,你会得到什么? –

+0

你的代码从命令行工作(我的默认时区是“America/Denver”)。我把它作为一个eclipse的bug。 –

回答

0

下面是一些示例代码。我明确地将我的服务器的默认时区设置为纽约时间,但您可能要遵循Jon Lin的提示并确定您自己的服务器的默认时区。例如,如果您在纽约,但正在使用托管在SF中的服务器并使用太平洋时间,那么这可能与任何区域中的预期时间相差3小时。

public void testTodayInIndia() { 
    // For demonstration, make my system act as though it's in New York 
    TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); 
    long oneDay = 86400000; 
    long fourYears = (365 * 4 + 1) * oneDay; 
    // Calculate 42 years after 1/1/1970 UTC 
    Date now = new Date(fourYears * 10 + oneDay * 365 * 2 + 1); 
    TimeZone calcutta = TimeZone.getTimeZone("Asia/Kolkata"); 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    // Since unspecified, this output will show the date and time in New York 
    assertEquals("2011-12-31 19:00:00", formatter.format(now)); 
    // After setting the formatter's time zone, output reflects the same instant in Calcutta. 
    formatter.setTimeZone(calcutta); 
    assertEquals("2012-01-01 05:30:00", formatter.format(now)); 
} 
0

可以使用的SimpleDateFormat和Date类,如下图所示:

Date date = new Date(); 
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(); 
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York")); 
    System.out.println(simpleDateFormat.format(date)); 

有不同的时区,你可以使用“美国/纽约”这样的“亚洲/加尔各答”取代。

相关问题