0

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();
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Jalal Ahmad
  • 77
  • 1
  • 7
  • Try Joda time API. http://stackoverflow.com/questions/14331063/how-to-get-properly-current-date-and-time-in-joda-time – Vivin Sep 25 '15 at 15:01
  • please be patient as i am new to this site and also use simple code as much as possible thanks in advance – Jalal Ahmad Sep 25 '15 at 15:01
  • 3
    *"Dynamic Date and Time for a specific country"* My country (Australia) spans 2-3 time zones, North America is about the same (for the mainland below Canada part) and Russia crosses about 10. For many countries there is no 'one specific time' . – Andrew Thompson Sep 25 '15 at 15:15

3 Answers3

2

java.time

You are using old classes (java.util.Date/.Calendar) that are now supplanted in Java 8 and later by the new java.time framework.

Time zone is an adjustment into someone's wall-clock time while following a set of rules for offset-from-UTC, Daylight Saving Time, and other anomalies. Use proper time zone names, never the 3-4 letter codes such as "EST" or "IST".

Locale determines the formatting of a String representation of a date-time value according to cultural norms of style and a particular human language (French, German, whatever). I suggest you let java.time do the work of formatting in a localized manner rather than you controlling the formatting. The enum FormatStyle to choose shorter or longer formats.

An Instant is a moment on the timeline in UTC. We then adjust into a time zone. Lastly create a string based on a particular Locale's formatting.

Instant instant = Instant.now();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale );
String output = zdt.format( formatter );

Dump to console.

System.out.println( "instant: " + instant );
System.out.println( "zdt: " + zdt );
System.out.println( "output: " + output );

When run.

instant: 2015-09-26T04:59:34.651Z
zdt: 2015-09-26T00:59:34.651-04:00[America/Montreal]
output: samedi 26 septembre 2015 0 h 59 EDT
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Sir where and how to use this code , i need just a method which i call and my jLable "lab_date" is set to the dynamic time. I want to set it to Pakistan Time – Jalal Ahmad Sep 26 '15 at 18:55
  • @JalalAhmad What is "dynamic time"? I suspect you mean the current moment. I showed how to do that in my Answer. `Instant.now` gives you the current moment in UTC. To adjust into a locality, apply a `ZoneId` to get a `ZonedDateTime`. Follow link I gave for proper time zones to find a desired zone such as [`Asia/Karachi`](https://en.wikipedia.org/wiki/Asia/Karachi), calling `ZonedDateTime.ofInstant` as seen above. Specify a Locale appropriate to the human language and cultural norms for your users. To automatically update, learn about Swing Timer or `ScheduledExecutorService`. – Basil Bourque Jun 25 '16 at 02:19
1

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()));
fabien t
  • 358
  • 1
  • 9
  • 2
    Locale is not related to time zone. One affects formatting. The other affects the actual value. – Matt Johnson-Pint Sep 25 '15 at 15:44
  • Your are right but the SimpleDateFormat do the job for us i think ? – fabien t Sep 25 '15 at 16:16
  • Thanks for this kindness but sir its giving an error in this line lab_date.setText(sdf.format(new Date())) ; no suitable constructor for Date()... something like this. i copied only the method and over-pasted on the old one and the upper three variables i declared as global in my JFrame class named as HomeFrame – Jalal Ahmad Sep 26 '15 at 18:49
  • in your import wich Date is used ? copy paste the Date import please – fabien t Sep 26 '15 at 18:52
  • now fine but sir how to do it for pakistan, as the time is running 2 hours ahead of my country – Jalal Ahmad Sep 27 '15 at 11:00
  • In theory, nothing more that call ´Locale.getDefault()´, it will give you the Locale of your Operating System, and the Locale does retrieve the good TomeZone for You ! But Pakistan don't have the appropriate Locale default, define in Locale, so it seam appear another question no ? We need to work as required by site i think – fabien t Sep 27 '15 at 12:36
  • it is 2:17 PM this time on my OS while my Loccale.getDefault(); gives me 04:17... this is the problem – Jalal Ahmad Sep 28 '15 at 09:19
0

It is simple, to get date and day of your region.

Date date = new Date();
System.out.println(date);

Output:

Tue May 15 00:36:48 PKT 2018

Muhammad Abdullah
  • 305
  • 1
  • 2
  • 10