UTC时间和GMT时间工具类JAVA源码

峰哥代码 发表于:2018-08-03 09:15 阅读: 411次

UTC时间 又叫做世界标准时间,可以理解为一个世界统一时间标准;GMT时间就是大家常听见的格林威治平均时间;今天在项目中,用到了两种时间,记录一下工具类代码以后备用。

package demo;

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

/**   
 * @ProjectName:  kumapai.com 
 * @Description:  UTC时间 工具类  
 * @Author:       酷码派   
 * @Version:      [v1.0] 
 */
public class UTCTimeUtil {

    // 取得本地时间:
    private Calendar cal = Calendar.getInstance();
    // 取得时间偏移量:
    private int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
    // 取得夏令时差:
    private int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);

    public static void main(String[] args) {
        UTCTimeUtil gc = new UTCTimeUtil();
        long mill = gc.getUTCTimeStr();
        gc.setUTCTime(mill);

        SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        Date d = new Date();
        String formattedTime = output.format(d);
        System.out.println(formattedTime);

    }

    public long getUTCTimeStr() {

        System.out.println("local millis = " + cal.getTimeInMillis()); // 等效System.currentTimeMillis() , 统一值,不分时区

        // 从本地时间里扣除这些差量,即可以取得UTC时间:
        cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));

        long mills = cal.getTimeInMillis();
        System.out.println("UTC = " + mills);

        return mills;
    }

    public void setUTCTime(long millis) {

        cal.setTimeInMillis(millis);

        SimpleDateFormat foo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = foo.format(cal.getTime());
        System.out.println("GMT time= " + time);

        // 从本地时间里扣除这些差量,即可以取得UTC时间:
        cal.add(java.util.Calendar.MILLISECOND, (zoneOffset + dstOffset));
        time = foo.format(cal.getTime());
        System.out.println("Local time = " + time);

    }

    public void getGMTTime() {
        //mothed 2
        TimeZone gmtTime = TimeZone.getTimeZone("GMT");
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
        format.setTimeZone(gmtTime);
        System.out.println("GMT Time: " + format.format(date));

        //method 2
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTimeZone(gmtTime);
        //System.out.println(calendar1.getTime());    //时区无效
        //System.out.println(calendar1.getTimeInMillis()); //时区无效
        System.out.println("GMT hour = " + calendar1.get(Calendar.HOUR));
    }
}
酷码派 [KuMaPai.COM] - 陕ICP备案证 18010024号-2