2013-02-03 118 views
0

我在时钟上创建Java GUI,要求用户从当前时间更改时间。我有系统时间和用户时间。应该是什么代码,以便显示用户时间。该foolowing代码我使用:如何将当前时间更改为用户时间

 Date curDate = new Date(); 
     //changeTime i have got from the user 
     double time=0; 
     if(curDate.getTime()- changeTime.getTime() > 0){ 
      time = curDate.getTime() - changeTime.getTime(); 
      time = time/(1000); 
     } 
     else{ 
      time = changeTime.getTime()-curDate.getTime(); 
      time = time/(1000); 
     } 
     if(changeTime.getHours()==0 && changeTime.getMinutes()==0){ 
      time=0; 
     } 
     curDate.setHours(curDate.getHours()+(int)time/(3600)); 
     curDate.setMinutes(curDate.getMinutes()+((int)time/60)%60); 

回答

1

一个new Date()是“旨在反映协调世界时(世界标准时间)。”用户在时钟上看到的内容取决于TimeZone,这可以在用于呈现日期的DateFormat中指定。下面的例子打印格林尼治标准时间相同的时刻,以及从纽约到柏林的一系列时区。

附录:我发现它的帮助想Date模型DateFormat作为模型的视图

 
03-Feb-2013 18:01:42 GMT GMT 1359914502673 
03-Feb-2013 13:01:42 EST America/New_York 1359914502673 
03-Feb-2013 14:01:42 AST America/Aruba 1359914502673 
03-Feb-2013 15:01:42 ART America/Buenos_Aires 1359914502673 
03-Feb-2013 16:01:42 BRST America/Sao_Paulo 1359914502673 
03-Feb-2013 17:01:42 AZOT Atlantic/Azores 1359914502673 
03-Feb-2013 18:01:42 GMT Europe/London 1359914502673 
03-Feb-2013 19:01:42 CET Europe/Berlin 1359914502673 

包日期;

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

/** @see http://stackoverflow.com/a/14675418/230513 */ 
public class TestSDF { 

    private static final String s = "dd-MMM-yyyy HH:mm:ss zz"; 
    private static final DateFormat f = new SimpleDateFormat(s); 

    public static void main(String[] args) { 
     Date date = new Date(); 
     print("GMT", date); 
     print("America/New_York", date); 
     print("America/Aruba", date); 
     print("America/Buenos_Aires", date); 
     print("America/Sao_Paulo", date); 
     print("Atlantic/Azores", date); 
     print("Europe/London", date); 
     print("Europe/Berlin", date); 
    } 

    private static void print(String tz, Date d) { 
     f.setTimeZone(TimeZone.getTimeZone(tz)); 
     System.out.println(f.format(d) 
      + " " + tz 
      + " " + d.getTime()); 
    } 
} 
0

一个简单的方法是根据用户的时间是获取系统时间addsubtract

例如系统时间是下午两点,用户改变时至下午四时然后只需2个小时,增加系统时间,并显示在您需要的用户时间字段

+0

我粘贴了代码,但我没有得到正确的结果。 –

+1

没有得到正确的结果?你得到了什么样的错误结果 – exexzian

相关问题