Java Calendar Adjust adjustCalendarToLocalTime(Calendar cal)

Here you can find the source of adjustCalendarToLocalTime(Calendar cal)

Description

Needed to rectify the interpretation of timestamp values in calendar objects.

License

Open Source License

Parameter

Parameter Description
cal a parameter

Declaration

public static void adjustCalendarToLocalTime(Calendar cal) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;

import java.util.Date;

import java.util.TimeZone;

public class Main {
    /**/*from   w ww  .  j  a v a  2  s.  c o m*/
     * Needed to rectify the interpretation of timestamp values in calendar
     * objects. Background: timestamps in our log files are meant to be in local
     * time, but are interpreted as UTC when setting the calendar with
     * setTimeInMillis. This method adjusts the calendar by the offset between
     * local time and UTC so that it actually reflects the correct time.
     * 
     * IMPORTANT: This method needs to be called WHENEVER a calendar has been
     * instantiated with setTimeInMillis
     * 
     * @param cal
     */
    public static void adjustCalendarToLocalTime(Calendar cal) {
        Date date = cal.getTime();

        TimeZone tz = TimeZone.getTimeZone("CET");
        long msFromEpochGmt = date.getTime(); // gets the ms from 1970 in UTC
        // (as set with
        // setTimeInMillis)

        // gives you the current offset in ms from GMT at the date
        // msFromEpochGmt
        int offsetFromUTC = tz.getOffset(msFromEpochGmt);

        cal.setTimeInMillis(msFromEpochGmt + offsetFromUTC);
    }
}

Related

  1. adjustCalendar(Calendar calendar)
  2. adjustDate(Calendar calendar, int differenceInDay)
  3. adjustedMillis(Calendar cal)
  4. adjustToDayEnd(Calendar cal)
  5. adjustToFieldStart(Calendar cal, int[] fields)