Java日历功能问题 [英] problem on java calendar function

查看:172
本文介绍了Java日历功能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样声明了日历 SimpleDateFormat

calendar = Calendar.getInstance(TimeZone.getTimeZone("Malaysia"));
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MMMMM.dd hh:mm aaa");

或:

calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));

然后我称之为:

sdf.format(calendar.getTime());

,但结果不在正确的时区(+8小时)内。可能是什么问题?

but result is not in correct time zone (+8 hours). What could be the problem?

推荐答案

除非您要执行与日期/时间相关的计算,否则实例化Calendar毫无意义。给定的TimeZone。调用Calendar的 getTime()方法后,您将收到 Date 对象,无论哪种方式都没有时区(基于GMT ,实际上)。

Unless you are going to perform Date/Time related calculations, there is no point in instantiating Calendar with given TimeZone. After calling Calendar's getTime() method, you will receive Date object, which is timezone-less either way (GMT based, actually).

您需要做的是设置 TimeZone 来设置格式化程序。并且也不必担心传递自己的格式,已经内置了一个

What you need to do, is to set TimeZone for formatter instead. And also do not bother with passing your own format, there is a built-in already:

    // get current time
    // you could just as well use Date now = new Date();
    Calendar now = Calendar.getInstance();

    // Locale for formatter
    Locale malaysianLocale = new Locale("ms", "MY");
    // Default date and time format for Malaysia
    DateFormat defaultMalaysianFormatter = DateFormat.getDateTimeInstance(
            DateFormat.DEFAULT, DateFormat.DEFAULT, malaysianLocale);
    // This step is crucial
    TimeZone malaysianTimeZone = TimeZone.getTimeZone("Asia/Kuala_Lumpur");
    defaultMalaysianFormatter.setTimeZone(malaysianTimeZone);

    System.out.println(defaultMalaysianFormatter.format(now.getTime()));

此打印内容类似于 10 Mei 2011 2:30:05 AM ,我相信这是您想要的结果。

This prints something like 10 Mei 2011 2:30:05 AM, which I believe is your desired result.

这篇关于Java日历功能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆