Java Date Now getCurrentGMTTime()

Here you can find the source of getCurrentGMTTime()

Description

get current GMT time

License

Apache License

Return

Date

Declaration

public static Date getCurrentGMTTime() 

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  w w. j  a  v a2 s.c  om*/
     * get current GMT time
     * 
     * @return Date
     */
    public static Date getCurrentGMTTime() {
        return getGMTTime(getTime());
    }

    /**
     * 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. getCurrentDay(int model)
  2. getCurrentDay(String pattern)
  3. getCurrentDayBegin()
  4. getCurrentDayInyyyyMMdd()
  5. getCurrentFormattedTime()
  6. getCurrentHMS()
  7. getCurrentISO8601Date()
  8. getCurrentJnlpTimestamp()
  9. getCurrentLastDate()