特定国家/地区的动态日期和时间

Dynamic Date and Time for a specific country

我需要一种获取动态日期和时间的方法,以便在 Java Netbeans 中通过 dd/MM/yyyy 格式的标签将其显示在 JFrame 上。我用了一个,但比我的国家时间早了 2 小时。以下是我使用的方法:

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();
}

获取巴基斯坦国家日期/时间的示例说明:

    // 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()));

java.time

您使用的是旧的 类 (java.util.Date/.Calendar),现在已在 Java 8 和更高版本中被新的 java.time 框架取代。

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,绝不是 "EST" 或 "IST".

等 3-4 字母代码

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 选择较短或较长的格式。

Instant 是 UTC 时间轴上的一个时刻。然后我们调整到一个时区。最后根据特定语言环境的格式创建一个字符串。

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 );

转储到控制台。

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

当运行.

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

获取您所在地区的日期和日期很简单。

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

输出:

2018 年 5 月 15 日星期二00:36:48