Android时间工具类 本地转UTC,UTC转本地

  package com.peopleapp.en.util;

import android.content.Context;
import android.text.TextUtils;
import android.text.format.DateFormat;

import com.peopleapp.en.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class TimeUtil {

    private static final int seconds_of_1minute = 60;
    private static final int seconds_of_1hour = 60 * 60;
    private static final int seconds_of_2hour = 2 * 60 * 60;
    private static final int seconds_of_3hour = 3 * 60 * 60;

    private static final String YMDHMS_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String search_DateFormat = "MM/dd/yyyy HH:mm:ss";
    private static final String TIME_ZERO = "00:00";
    private static final String TIME_MAX = "23:59:59";

    public static Date stringConvertDate(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date data = null;
        try {
            data = sdf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return data;
    }

    public static String timeAgo(Context context, long createdTime) {
        return timeAgo(context, new Date(createdTime));
    }

    public static String timeAgo(Context context, Date createdTime) {
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA);
        if (createdTime != null) {
            long agoTimeInMin = (new Date(System.currentTimeMillis()).getTime() - createdTime.getTime()) / 1000 / 60;
            if (agoTimeInMin <= 1) {
                return context.getString(R.string.just_now);
            } else if (agoTimeInMin <= 60) {
                return agoTimeInMin + context.getString(R.string.mins_ago);
            } else if (agoTimeInMin <= 60 * 24) {
                return agoTimeInMin / 60 + context.getString(R.string.hours_ago);
            } else if (agoTimeInMin <= 60 * 24 * 2) {
                return agoTimeInMin / (60 * 24) + context.getString(R.string.days_ago);
            } else {
                return format.format(createdTime);
            }
        } else {
            return format.format(new Date(0));
        }
    }

    public static String getDateTimeAgo(Context context, long timeStamp) {
        return timeAgo(context, new Date(timeStamp));
    }

    public static String getUSDateTimeFormat(long timeStamp) {
        SimpleDateFormat usSdf = new SimpleDateFormat("HH:mm, MMMM dd, yyyy", Locale.US);
        return usSdf.format(new Date(timeStamp));
    }

    public static String getCurrentTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * local ---> UTC
     *
     * @return
     */
    public static String Local2UTC() {
        SimpleDateFormat sdf = new SimpleDateFormat(YMDHMS_FORMAT);
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        String gmtTime = sdf.format(new Date());
        return gmtTime;
    }

    /**
     * UTC --->local
     *
     * @param utcTime UTC
     * @return
     */
    public static String utc2Local(String utcTime) {
        try {
            if (TextUtils.isEmpty(utcTime)) {
                return "";
            }
            SimpleDateFormat utcFormater = new SimpleDateFormat(YMDHMS_FORMAT);
            utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date gpsUTCDate = null;
            try {
                gpsUTCDate = utcFormater.parse(utcTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat localFormater = new SimpleDateFormat(YMDHMS_FORMAT);
            localFormater.setTimeZone(TimeZone.getDefault());
            String localTime = localFormater.format(gpsUTCDate.getTime());
            return localTime;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param tTime
     * @return
     */
    public static String getTimeRange(Context context, String tTime) {
        String mTime = "";
        try {
            mTime = utc2Local(tTime);
            if (TextUtils.isEmpty(mTime)) {
                return "";
            }
            SimpleDateFormat sdf = new SimpleDateFormat(YMDHMS_FORMAT);
            sdf.setTimeZone(TimeZone.getDefault());
            Date curDate = new Date(System.currentTimeMillis());
            String dataStrNew = sdf.format(curDate);
            Date startTime = null;
            try {
                curDate = sdf.parse(dataStrNew);
                startTime = sdf.parse(mTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long between = (curDate.getTime() - startTime.getTime()) / 1000;
            int elapsedTime = (int) (between);
            if (elapsedTime < 0) {
                return context.getResources().getString(R.string.timeutils_default_oneminageo);
            }
            if (elapsedTime < seconds_of_1minute) {

                return context.getResources().getString(R.string.timeutils_default_oneminageo);
            }
            if (elapsedTime < seconds_of_1hour) {

                return elapsedTime / seconds_of_1minute + " " + context.getResources().getString(R.string.timeutils_default_moreminsageo);
            }
            if (elapsedTime < seconds_of_2hour) {

                return context.getResources().getString(R.string.timeutils_default_onehourageo);
            }
            if (elapsedTime < seconds_of_3hour) {

                return elapsedTime / seconds_of_1hour + " " + context.getResources().getString(R.string.timeutils_default_morehoursageo);
            }

            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }

        return context.getResources().getString(R.string.timeutils_default_threehoursageo);
    }

    public static String getTimeRange(Context context, long time) {
        long between = (System.currentTimeMillis() - time) / 1000;
        int elapsedTime = (int) (between);
        if (elapsedTime < 0) {
            return context.getResources().getString(R.string.timeutils_default_oneminageo);
        }
        if (elapsedTime < seconds_of_1minute) {

            return context.getResources().getString(R.string.timeutils_default_oneminageo);
        }
        if (elapsedTime < seconds_of_1hour) {

            return elapsedTime / seconds_of_1minute + " " + context.getResources().getString(R.string.timeutils_default_moreminsageo);
        }
        if (elapsedTime < seconds_of_2hour) {

            return context.getResources().getString(R.string.timeutils_default_onehourageo);
        }
        if (elapsedTime < seconds_of_3hour) {

            return elapsedTime / seconds_of_1hour + " " + context.getResources().getString(R.string.timeutils_default_morehoursageo);
        }
        return "";
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @return
     */
    public static String timeStamp2Date(long seconds, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(seconds));
    }

    public static String longToString(long longNum, String dateFormat) {
        if (TextUtils.isEmpty(dateFormat)) {
            dateFormat = YMDHMS_FORMAT;
        }
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        Date date = new Date(longNum);
        return format.format(date);
    }

    public static String secondsToTime(int time) {
        String timeStr = null;
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (time <= 0)
            return TIME_ZERO;
        else {
            minute = time / 60;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                hour = minute / 60;
                if (hour > 23)
                    return TIME_MAX;
                minute = minute % 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
            }
        }
        return timeStr;
    }

    public static String unitFormat(int i) {
        String retStr = null;
        try {
            if (i >= 0 && i < 10)
                retStr = "0" + Integer.toString(i);
            else
                retStr = "" + i;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retStr;
    }

    public static long searchTimeToLong(String time) {
        if (TextUtils.isEmpty(time)) {
            return 0L;
        }
        try {
            String[] split = time.split(" ");
            String tempTime = split[0] + " " + split[1];
            int diff = 0;
            if ("pm".equals(split[2])) {
                diff = 1000 * 12 * 60 * 60;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(search_DateFormat);
            sdf.setTimeZone(TimeZone.getDefault());
            Date startTime = null;
            startTime = sdf.parse(tempTime);
            return (startTime.getTime() + diff);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    public static String searchTimeFormat(String time) {
        if (TextUtils.isEmpty(time)) {
            return "";
        }
        try {
            String date = (String) DateFormat.format("yyyy-MM-dd HH:mm:ss", searchTimeToLong(time));
            return date;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}

unit uTimeZonesMgr; interface uses Windows, SysUtils, Classes, Registry, DateUtils; type {* 用于读取时区注册表TZI(长度为44)的属性值,存储时区信息 *} PRegTZIInfo = ^TRegTZIInfo; TRegTZIInfo = record Bias: Longint; StandardBias: Longint; DaylightBias: Longint; StandardDate: TSystemTime; DaylightDate: TSystemTime; end; {* 单个时区管理对象 *} TTimeZone = class private FTimeZoneName: string; //时区的显示名 FDisplay: string; //夏令时的名字 FDlt: string; //时区标准名字 FStd: string; //是Time zone information的缩写,描述时区的一些重要信息 FTZI: PRegTZIInfo; function GetSelfTimeZoneInformation: TTimeZoneInformation; public constructor Create; destructor Destroy; override; function UTCToLocalDateTime(const AUTC: TDateTime; var ALocalDateTime: TDateTime): Boolean; function LocalDateTimeToUTC(const ALocalDateTime: TDateTime; var AUTC: TDateTime): Boolean; public property TimeZoneName: string read FTimeZoneName write FTimeZoneName; property Display: string read FDisplay write FDisplay; property Dlt: string read FDlt write FDlt; property Std: string read FStd write FStd; property TZI: PRegTZIInfo read FTZI write FTZI; end; {* 所有时区管理对象 *} TTimeZones = class private FTimeZoneKeyPath: string; FTimeZoneList: TStringList; FDefaultTimeZone: TTimeZone; procedure CollectTimeZone; procedure DestoryTimeZones; procedure CheckISDefaultTimeZone(ATimeZone: TTimeZone); public constructor Create; destructor Destroy; override; function FindTimeZone(const ADisplay: string): TTimeZone; public property TimeZoneList: TStringList read FTimeZoneList; property DefaultTimeZone: TTimeZone read FDefaultTimeZone; end; implementation { TTimeZones } procedure TTimeZones.CheckISDefaultTimeZone(ATimeZone: TTimeZone); var DefaultTimeZone: TTimeZoneInformation; begin GetTimeZoneInformation(DefaultTimeZone); if (ATimeZone.TZI.Bias = DefaultTimeZone.Bias) and (ATimeZone.Std = DefaultTimeZone.StandardName) then FDefaultTimeZone := ATimeZone; end; procedure TTimeZones.CollectTimeZone; var reg, tempReg: TRegistry; tempKeyPath: string; tempTimeZoneStrings: TStrings; iCir: Integer; tempTimeZone: TTimeZone; begin reg := TRegistry.Create; try reg.RootKey := HKEY_LOCAL_MACHINE; reg.OpenKey(FTimeZoneKeyPath, False); tempTimeZoneStrings := TStringList.Create; try reg.GetKeyNames(tempTimeZoneStrings); for iCir := 0 to tempTimeZoneStrings.Count - 1 do begin tempKeyPath := FTimeZoneKeyPath + '\' + tempTimeZoneStrings.Strings[iCir]; tempReg := TRegistry.Create; try tempReg.RootKey := HKEY_LOCAL_MACHINE; tempReg.OpenKey(tempKeyPath, False); tempTimeZone := TTimeZone.Create; tempTimeZone.TimeZoneName := tempTimeZoneStrings.Strings[iCir]; tempTimeZone.Display := tempReg.ReadString('Display'); tempTimeZone.Std := tempReg.ReadString('Std'); tempTimeZone.Dlt := tempReg.ReadString('Dlt'); tempReg.ReadBinaryData('TZI', tempTimeZone.TZI^, SizeOf(TRegTZIInfo)); FTimeZoneList.AddObject(tempTimeZone.Display, tempTimeZone); if FDefaultTimeZone = nil then CheckISDefaultTimeZone(tempTimeZone); finally tempReg.CloseKey; tempReg.Free; end; end; finally tempTimeZoneStrings.Free; end; finally reg.CloseKey; reg.Free; end; end; constructor TTimeZones.Create; begin FTimeZoneKeyPath := '\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones'; FTimeZoneList := TStringList.Create; FTimeZoneList.Sorted := True; FDefaultTimeZone := nil; CollectTimeZone; end; procedure TTimeZones.DestoryTimeZones; var iCir: Integer; tempTimeZone: TTimeZone; begin for iCir := 0 to FTimeZoneList.Count - 1 do begin tempTimeZone := TTimeZone(FTimeZoneList.Objects[iCir]); tempTimeZone.Free; end; FTimeZoneList.Clear; FTimeZoneList.Free; end; destructor TTimeZones.Destroy; begin DestoryTimeZones(); inherited; end; function TTimeZones.FindTimeZone(const ADisplay: string): TTimeZone; var iIndex: Integer; begin Result := nil; FTimeZoneList.Sort; if FTimeZoneList.Find(ADisplay, iIndex) then begin Result := TTimeZone(FTimeZoneList.Objects[iIndex]); end; end; { TTimeZone } constructor TTimeZone.Create; begin FTZI := GetMemory(SizeOf(TRegTZIInfo)); FillMemory(FTZI, SizeOf(TRegTZIInfo), 0); end; destructor TTimeZone.Destroy; begin FreeMemory(FTZI); inherited; end; function TTimeZone.GetSelfTimeZoneInformation: TTimeZoneInformation; begin GetTimeZoneInformation(Result); Result.Bias := TZI^.Bias; Result.StandardBias := TZI^.StandardBias; Result.StandardDate := TZI^.StandardDate; Result.DaylightBias := TZI^.DaylightBias; Result.DaylightDate := TZI^.DaylightDate; end; function TTimeZone.LocalDateTimeToUTC(const ALocalDateTime: TDateTime; var AUTC: TDateTime): Boolean; var tempLocalToLocal: TDateTime; iMilliSecond: Int64; begin Result := UTCToLocalDateTime(ALocalDateTime, tempLocalToLocal); if Result then begin if tempLocalToLocal > ALocalDateTime then begin iMilliSecond := MilliSecondsBetween(tempLocalToLocal, ALocalDateTime); AUTC := IncMilliSecond(ALocalDateTime, iMilliSecond * -1); end else begin iMilliSecond := MilliSecondsBetween(ALocalDateTime, tempLocalToLocal); AUTC := IncMilliSecond(ALocalDateTime, iMilliSecond); end; Result := True; end; end; function TTimeZone.UTCToLocalDateTime(const AUTC: TDateTime; var ALocalDateTime: TDateTime): Boolean; var TimeZone: TTimeZoneInformation; stUTC, stLC: SYSTEMTIME; begin Result := False; TimeZone := GetSelfTimeZoneInformation; DateTimeToSystemTime(AUTC, stUTC); if SystemTimeToTzSpecificLocalTime(@TimeZone, stUTC, stLC) then begin ALocalDateTime := SystemTimeToDateTime(stLC); Result := True; end; end; end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lidongxiu0714

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值