2014-02-22 109 views
1

在Java中如何使用Joda-Time获取日期和时间使用时区。服务器正在运行UTC +0300。但我需要使用UTC +0530,即印度标准时间。我需要使用这样的java joda-time获取日期时间

DateTimeZone zone = DateTimeZone.forID("Asia/Calcutta"); 

可是如何才能让日期和时间格式为:dd-MM-yyyy hh:mm:ss

任何帮助是极大的赞赏。

+3

http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormatter.html#withZone(org.joda.time.DateTimeZone) – PopoFibo

回答

1

你需要一个DateTimeFormatter

private static final DateTimeFormatter FORMATTER 
    = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss"); 

然后你就可以.print()DateTime

// Returns a String 
FORMATTER.print(new DateTime(zone)); 
1

其他的答案是局部的。这里有更多信息。

要调整时区,您可以:

  • 分配了不同的时区,创建一个新的DateTime实例。
  • 让格式器在创建日期时间的字符串表示形式时应用时区。
DateTime dateTimeMoscow = new DateTime(DateTimeZone.forID("Europe/Moscow")); 
DateTime dateTimeIndia = dateTimeMoscow.withZone(DateTimeZone.forID("Asia/Kolkata")); 
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy hh:mm:ss").withZone(DateTimeZone.forID("Asia/Kolkata")); 
String output = formatter.print(dateTimeMoscow); // Formatter adjusts zone from Moscow to Kolkata.