Takes a calendar object representing a date/time, ignores its current time zone - Android java.util

Android examples for java.util:Timezone

Description

Takes a calendar object representing a date/time, ignores its current time zone

Demo Code

/*/*from   ww  w .  jav a 2s .c  om*/
 * Copyright 2014 Kevin Quan (kevin.quan@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.util.Calendar;
import java.util.TimeZone;

public class Main {
    /**
     * Takes a calendar object representing a date/time, ignores its current time zone (which should be the default time zone)
     * applies that date/time to the sourceTimeZone and returns the relative date/time in the current time zone. 
     * 
     * For example, given an input of 13:00 EST and source time zone PST, it will return 16:00 EST 
     * 13:00 EST = 18:00 GMT = 10:00 PST
     *  
     * @param calendar
     * @param sourceTimeZone
     * @return
     */
    public static Calendar convertToTimeZone(Calendar calendar,
            TimeZone sourceTimeZone) {
        Calendar result = Calendar.getInstance();
        // i.e., 13:00 EST becomes 08:00 GMT
        long originalTimeInUtc = calendar.getTimeInMillis()
                + calendar.getTimeZone().getOffset(
                        calendar.getTimeInMillis());
        // 08:00 GMT becomes 16:00 PST
        long sourceTime = originalTimeInUtc
                - sourceTimeZone.getOffset(originalTimeInUtc);
        result.setTimeZone(sourceTimeZone);
        result.setTimeInMillis(sourceTime);
        /*
        Log.d(TAG, "Converting "+DEBUG_CALENDAR_OUTPUT.format(new Date(calendar.getTimeInMillis()))
                +" in ["+sourceTimeZone.getDisplayName()+"] to ["+TimeZone.getDefault().getDisplayName()
                +"] resulting in "+DEBUG_CALENDAR_OUTPUT_WITH_TIMEZONE.format(new Date(result.getTimeInMillis())));
        Log.d(TAG, "Original time in UTC = "+DEBUG_CALENDAR_OUTPUT.format(new Date(originalTimeInUtc)));
        Log.d(TAG, "Original time in source time zone = "+DEBUG_CALENDAR_OUTPUT.format(new Date(sourceTime)));
         */
        return result;
    }
}

Related Tutorials