local Time to utc Time - Android java.util

Android examples for java.util:Time

Description

local Time to utc Time

Demo Code


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.annotation.SuppressLint;
import android.util.Log;

public class Main{
    private static final String TAG = TimeUtil.class.getName();
    //from ww w  .  jav a  2 s.  co  m
    public static long localTime2utcTime(String localTime, String dateFormat) {
        long utcTimes = 0;
        if (localTime != null && localTime.length() > 0) {
            SimpleDateFormat localFormater = new SimpleDateFormat(
                    dateFormat);
            localFormater.setTimeZone(TimeZone.getDefault());
            Date date;
            try {
                date = localFormater.parse(localTime);
                utcTimes = dateToUtcTime(date);
            } catch (Exception e) {
                Log.e(TAG, "local time:" + localTime
                        + " is invalid time string");
                return utcTimes;
            }
        } else {
            new Exception("Date is not null");
        }
        return utcTimes;
    }
    
    public static long dateToUtcTime(Date date) {
        if (date != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar.getTimeInMillis();
        } else {
            return 0;
        }
    }
}

Related Tutorials