在java中获取不同的时区

时间:2015-03-14 07:39:07

标签: java time

在java中以millis获取当前时间我们有方法,但这需要系统时间。但是我说印度时间和苏黎世时间如何从我的系统中选择一个特定的时区?

1 个答案:

答案 0 :(得分:0)

您必须更改系统压缩程序中的时区,或者必须计算当前时区和所需时区之间的差异。然后将差异添加到当前时区。您将获得所需的时区时间。以下是一些可以使用它们的方法。

package com.jts1.service.timeconverter;

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

public class TimeConverterUtil {
private int offsetHours;
private int offsetMinutes;
private int selectedTimeZoneOffset;
private int currentTimeZoneoffset;
private int selectedtimeZoneOffsetMinutes;
private int dayLightSavings;
private long greenwichMeanTimeMilliSeconds;
private long localTimeMilliSeconds;
private String selectedTimeZoneType;
private String selectedTimeZoneName;
private String[] timeZoneIDs = TimeZone.getAvailableIDs();
private Calendar localCalendar;
private TimeZone selectedtimezone;
private TimeZone currentTimeZone;

@SuppressLint("SimpleDateFormat")
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
        "EEEE, dd MMMM yyyy HH:mm:ss");

public int getSelectedTimeZoneOffset(int timeZoneTypePosition) {
    selectedTimeZoneType = timeZoneIDs[timeZoneTypePosition];
    selectedtimezone = TimeZone.getTimeZone(selectedTimeZoneType);
    selectedTimeZoneName = selectedtimezone.getDisplayName();
    selectedTimeZoneOffset = selectedtimezone.getRawOffset();
    if (selectedtimezone.inDaylightTime(new Date())) {
        dayLightSavings = selectedtimezone.getDSTSavings();
    }
    selectedTimeZoneOffset = selectedTimeZoneOffset - dayLightSavings;
    return selectedTimeZoneOffset;
}

public String getSelectedTimeZoneName(int timeZoneTypePosition) {
    selectedTimeZoneType = timeZoneIDs[timeZoneTypePosition];
    selectedtimezone = TimeZone.getTimeZone(selectedTimeZoneType);
    selectedTimeZoneName = selectedtimezone.getDisplayName();
    return selectedTimeZoneName;
}

public long getGreenwichMeanTime() {
    localCalendar = Calendar.getInstance();
    localTimeMilliSeconds = localCalendar.getTimeInMillis();
    currentTimeZone = Calendar.getInstance().getTimeZone();
    currentTimeZoneoffset = currentTimeZone.getRawOffset();
    if (currentTimeZone.inDaylightTime(new Date())) {
        currentTimeZoneoffset = currentTimeZoneoffset
                + currentTimeZone.getDSTSavings();
    }
    greenwichMeanTimeMilliSeconds = localTimeMilliSeconds
            - currentTimeZoneoffset;
    return greenwichMeanTimeMilliSeconds;
}

public int getOffsetHoursToGMT(int selectedTimeZoneOffset) {
    selectedtimeZoneOffsetMinutes = selectedTimeZoneOffset / (60 * 1000);
    offsetHours = selectedtimeZoneOffsetMinutes / 60;
    return offsetHours;
}

public int getOffsetMinutesToGMT(int selectedTimeZoneOffset) {
    selectedtimeZoneOffsetMinutes = selectedTimeZoneOffset / (60 * 1000);
    offsetMinutes = selectedtimeZoneOffsetMinutes % 60;
    return offsetMinutes;
}

}