我有以下将我的自定义DMY(日期,月份,年份)对象转换为日期的方法。

public static Date serverCreateDateFromDMY(DMY pDMY, TimeZone pTimeZone)
    {
        Calendar vCalendar = Calendar.getInstance(pTimeZone);
        vCalendar.set(Calendar.YEAR, pDMY.getYear());
            // Below line is because DMY month counts are 1-indexed
            // and Date month counts are 0-indexed
        vCalendar.set(Calendar.MONTH, pDMY.getMonthOfYear() - 1);
        vCalendar.set(Calendar.DAY_OF_MONTH, pDMY.getDayOfMonth());
        System.out.println(vCalendar.getTime());
        TimeUtilsServer.zeroCalendarHoursAndBelow(vCalendar);
        System.out.println(vCalendar.getTime());
        return vCalendar.getTime();
    }


public static void zeroCalendarHoursAndBelow(Calendar pToZero)
    {
        pToZero.set(Calendar.HOUR_OF_DAY, 0);
        pToZero.set(Calendar.MINUTE, 0);
        pToZero.set(Calendar.SECOND, 0);
        pToZero.set(Calendar.MILLISECOND, 0);
    }


到serverCreateDateFromDMY()方法,我传递了以下参数:DMY = 20120424,而TimeZone是:America / New_York。应用程序在我的时区(IST)本地运行。

根据以上输入,将输出以下输出。

Tue Apr 24 14:43:07 IST 2012

Tue Apr 24 09:30:00 IST 2012


如您所见,最后的输出时间并未归零。有什么建议吗?

@Marko,是的,我了解DateFormat,并尝试了以下示例。但日期仍会显示时间,而不是归零。

TimeZone tz = TimeZone.getTimeZone("America/New_York");
        Calendar vCalendar = Calendar.getInstance(tz);
        vCalendar.set(Calendar.YEAR, 2012);

        vCalendar.set(Calendar.MONTH, 4 - 1);
        vCalendar.set(Calendar.DAY_OF_MONTH, 24);
        DateFormat df = DateFormat.getDateTimeInstance();
        df.setTimeZone(tz);
        System.out.println(df.format(vCalendar.getTime()));

         vCalendar.set(Calendar.HOUR_OF_DAY,     vCalendar.getActualMinimum(Calendar.HOUR_OF_DAY));
        vCalendar.set(Calendar.MINUTE, vCalendar.getActualMinimum(Calendar.MINUTE));
        vCalendar.set(Calendar.SECOND, vCalendar.getActualMinimum(Calendar.SECOND));
        vCalendar.set(Calendar.MILLISECOND,   vCalendar.getActualMinimum(Calendar.MILLISECOND));
        System.out.println(df.format(vCalendar.getTime()));

最佳答案

……您比纽约时间早9:30。您将时间设置为纽约时间午夜,并将其读出为您所在区域的时间。请注意,getTime返回一个Date,它不是时区可配置的。如果要指定打印结果的时区,则需要DateFormat

关于java - java.util.Calendar和timeZones的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10295311/

10-09 09:22