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

时间:2015-09-25 15:00:05

标签: java date timezone locale gregorian-calendar

我需要一种方法来获取动态日期和时间,以便通过Java Netbeans中JFrame格式的标签在dd/MM/yyyy上显示它。我使用了一个,但比我的国家时间提前了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();
}

3 个答案:

答案 0 :(得分:1)

java.time

您正在使用旧的类(java.util.Date/.Calendar),这些类现在已在Java 8及更高版本的java.time框架中取代。

Time zone是对某人的wall-clock time进行调整,同时遵循一系列偏离 - UTCDaylight Saving Time和其他异常的规则。使用proper time zone names,不要使用3-4个字母代码,例如“EST”或“IST”。

Locale根据样式的文化规范和特定的人类语言(法语,德语,等等)确定日期时间值的字符串表示的格式。我建议你让java.time以本地化方式完成格式化工作,而不是控制格式化。枚举FormatStyle可选择更短或更长的格式。

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 ); 是UTC时间轴上的一个时刻。然后我们调整到一个时区。最后根据特定的Locale格式创建一个字符串。

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

跑步时。

{{1}}

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

./gradlew wrapper --gradle-version 4.6

<强>输出:

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

相关问题