Java Time in GMT getGMTTime(Date localTime)

Here you can find the source of getGMTTime(Date localTime)

Description

get GMT Time from local time.

License

Apache License

Parameter

Parameter Description
localTime a parameter

Return

Date

Declaration

public static Date getGMTTime(Date localTime) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.text.DateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import java.util.TimeZone;

public class Main {
    public final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    /**/*  w  ww .  jav a 2s  . c  om*/
     * get GMT Time from local time.
     * 
     * @param localTime
     * @return Date
     */
    public static Date getGMTTime(Date localTime) {

        if (localTime == null)
            return null;
        return getTime(localTime, TimeZone.getDefault(), TimeZone.getTimeZone("GMT"));
    }

    public static Date getTime() {
        return Calendar.getInstance().getTime();
    }

    public static Date getTime(int field, int diff) {
        Calendar c = Calendar.getInstance();
        c.add(field, diff);
        return c.getTime();
    }

    /**
     * get time of dstTimeZone from time of srcTimeZone
     * 
     * @param time
     * @param srcTimeZone
     * @param dstTimeZone
     * @return Data
     */
    private static Date getTime(Date time, TimeZone srcTimeZone, TimeZone dstTimeZone) {
        if (time == null)
            return null;
        DateFormat df = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        df.setTimeZone(dstTimeZone);
        String gmtTime = df.format(time); // convert current time to gmt time.
        df.setTimeZone(srcTimeZone);
        try {
            return df.parse(gmtTime); // gmt time to date
        } catch (ParseException e) {
            return time;
        }

    }

    public static Date parse(String date, String format) throws ParseException {
        if (date == null)
            return null;

        SimpleDateFormat fmt = new SimpleDateFormat(format);

        return fmt.parse(date);
    }
}

Related

  1. getGmtFromTimeInMillis(String val)
  2. getGMTime()
  3. getGMTime()
  4. getGMTString(Date d)
  5. getGMTString(Date date, TimeZone tz)
  6. getGMTTime(final Date date)
  7. getGMTTimeStr(Date pageTime, int offset)
  8. getGmtTimeString(double startTime)