一个简单的设置时间,并用两种形式显示时间。
import javax.swing.*;
import java.text.DecimalFormat;
public class TimeTest {
public static void main(String args[]){
Time1 time = new Time1();
String output="The initial universal time is: "+time.toStandardString();
time.setTime(13,27,6);
output+="\n\nUniversal time after setTime is: "+time.toUniversalString()+"\nStandrad time after setTime is: "+time.toStandardString();
JOptionPane.showMessageDialog(null,output,"Testing Class Timel",JOptionPane.INFORMATION_MESSAGE );
System.exit(0);
}
}
import java.text.DecimalFormat;
/**
* Created by End on 15/12/12.
*/
public class Time1 extends Object{
private int hour ;
private int minute;
private int second;
public Time1(){
setTime(0,0,0);
}
public void setTime(int hour,int minute,int second){
this.hour=((hour>=0&&hour<24)?hour:0);
this.minute=((minute>=0&&minute<60)?minute:0);
this.second=((second>=0&&second<60)?second:0);
}
public String toUniversalString(){
DecimalFormat twoDigits=new DecimalFormat("00");
return twoDigits.format(hour)+":"+twoDigits.format(minute)+":"+twoDigits.format(second);
}
public String toStandardString(){
DecimalFormat twoDigits=new DecimalFormat("00");
return ((hour==12||hour==0)? 12: hour % 12) + ":" + twoDigits.format(minute)+":"+twoDigits.format(second)+(hour<12?"AM":"PM");
}
}