2015-11-27 72 views
0

我有一个时区,我做的事:如何从特定时区获得时间?

时区TZ = TimeZone.getTimeZone(“GMT-05:00” ); 日历C = Calendar.getInstance(TZ);

我怎样才能得到一个DateTime对象从该时区的正确时间?
如果我做c.getTime()我得到的当前时间,而不是时区的时间。

String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+ 
      String.format("%02d" , c.get(Calendar.MINUTE))+":"+ 
.     String.format("%02d" , c.get(Calendar.SECOND))+":"+ 
    .   String.format("%03d" , c.get(Calendar.MILLISECOND)); 

我得到了预期的时间,但我无法从此字符串创建有效的DateTime对象。
我该如何解决这个问题?

+0

你使用哪个版本的Java? 8或更少? – fge

+0

@fge:我使用Java 7 – Jim

+0

您提到了jodatime作为标签;你真的使用它?您的代码仅依赖于旧的API – fge

回答

0

其他可能获得和打印时间时区包括:

import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Date; 


public class TestDate { 

    public static void main(String[] args){ 
     Date date = new Date(); 
     DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); 
     String dateString = df.format(date); 

     System.out.println(dateString); 
    } 
} 
0

这可能是有益的看到此链接

TimeZone tz = TimeZone.getTimeZone("GMT+05:30"); 
Calendar c = Calendar.getInstance(tz); 
String time = String.format("%02d" , c.get(Calendar.HOUR_OF_DAY))+":"+ 
      String.format("%02d" , c.get(Calendar.MINUTE))+":"+ 
.     String.format("%02d" , c.get(Calendar.SECOND))+":"+ 
    .   String.format("%03d" , c.get(Calendar.MILLISECOND)); 
0

您需要使用DateTime.WithZone方法

TimeZone timeZone = TimeZone.getTimeZone("GMT-05:00"); 
    DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(timeZone); 
    System.out.println(timeZone); 
    System.out.println(dateTimeZone); 
    DateTime dt = new DateTime(); 
    DateTime dtLondon = dt.withZone(dateTimeZone); 
    System.out.println(dtLondon); 
+0

我没有“forId”部分的信息 – Jim

+0

好的,我明白了,请仔细阅读更新的答案,然后...... @ Jim –

相关问题