I need a method for getting dynamic date and time to display it on the JFrame
through a label in the dd/MM/yyyy
format in Java Netbeans. I used one but that was 2 hours ahead of my country time. Following is the method I used:
public void currentDate(){
Thread clock = new Thread(){
public void run(){
for(;;){
//empty for will run forever
//System.out.print("p");
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int day = cal.get(Calendar.DAY_OF_MONTH);
int second = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);
int hour = cal.get(Calendar.HOUR);
lab_date.setText(day+"/"+(((month+1)<10)?"0"+(month+1):(month+1))+"/"+year+" "
+ hour+":"+minute+":"+second
);
try {
sleep(1000);//1000 miliseconds it will sleep which means one second sleep
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
};
clock.start();
}
A sample illustration to get Date / time for Pakistan country:
// create a simple date format instance
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 'T' HH:mm:ss");
// get the time zone of Paskistan country
TimeZone pakistan = TimeZone.getTimeZone("Asia/Karachi");
// set the time zone to the date format
sdf.setTimeZone(pakistan);
// print the date to the console
System.err.println(sdf.format(new Date()));