如何转换当地时间到utc?

时间:2016-02-29 14:06:30

标签: android datetime

我发现很多函数可以从utc转换为本地时间,但我没有找到如何从本地转换为utc?

这是从utc到本地使用,如何编辑从本地获取utc?

     public static String timezoneAwareDate(String date){
    // create simpledateformat for UTC dates in database
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date output;
    // parse time
    try{
        output = simpleDateFormat.parse(date);
    }catch (Exception e){
        // return current time
        output = new Date();
    }

    return output.toString();
}

2 个答案:

答案 0 :(得分:2)

public static java.util.Date getConvertedDate(java.util.Date date,String newTimeZone) {

    if(date != null) {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yy hh:mm a");
        df.setTimeZone(TimeZone.getTimeZone(newTimeZone));

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        String newdt = df.format(calendar.getTime());
        try {
            date = df.parse(newdt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    return date;
}

答案 1 :(得分:0)

在项目中添加此类,并将其本地方法用于utc或utc to local。

import java.util.TimeZone;

public final class Utility {
public static final TimeZone utcTZ = TimeZone.getTimeZone("UTC");

public static long toLocalTime(long time, TimeZone to) {
    return convertTime(time, utcTZ, to);
}

public static long toUTC(long time, TimeZone from) {
    return convertTime(time, from, utcTZ);
}

public static long convertTime(long time, TimeZone from, TimeZone to) {
    return time + getTimeZoneOffset(time, from, to);
}

private static long getTimeZoneOffset(long time, TimeZone from, TimeZone to)    {
    int fromOffset = from.getOffset(time);
    int toOffset = to.getOffset(time);
    int diff = 0;

    if (fromOffset >= 0){
        if (toOffset > 0){
            toOffset = -1*toOffset;
        } else {
            toOffset = Math.abs(toOffset);
        }
        diff = (fromOffset+toOffset)*-1;
    } else {
        if (toOffset <= 0){
            toOffset = -1*Math.abs(toOffset);
        }
        diff = (Math.abs(fromOffset)+toOffset);
    }
    return diff;
   }
}

如果你想更多关于这件事。这已在link

中得到解答