我的申请下载购物详情。 示例:伦敦时间凌晨5:30下载的购物详情。 现在,更改任何其他时区,以便按所选时区转换下载时间。 时区正在更改日期/时间下的设置。如何以编程方式实现这一目标?那么如何根据时区选择转换下载时间?
试试这个,
我假设您已经在伦敦时间中午12:00下载了购物详情。假设您使用的是24小时格式,我正在使用HH。如果要将其转换为设备默认时区,请使用DateFormat设置时区并格式化现有时间。
TimeZone.getDefault(),它给出了设备的默认时区。
try {
DateFormat utcFormat = new SimpleDateFormat("HH:mm");
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = utcFormat.parse("12:00");
DateFormat deviceFormat = new SimpleDateFormat("HH:mm");
deviceFormat.setTimeZone(TimeZone.getDefault()); //Device timezone
String convertedTime = deviceFormat.format(date);
} catch(Exception e){
}
不,没有用于更改时间或时区的API ..无法以编程方式更改手机的时区。
基于@Raghavendra解决方案,这可以是一种便携式方法,如下所示:
/**
* converts GMT date and/or time with a certain pattern into Local Device TimeZone
* Example of dateTimePattern:
* "HH:mm",
* "yyyy-MM-dd HH:mm:ss",
* "yyyy-MM-dd HH:mm"
* Ex of dateTimeGMT:
* "12:00",
* "15:23",
* "2019-02-22 09:00:21"
* This assumes 24hr format
*/
@SuppressLint("SimpleDateFormat")
private String getDeviceDateTimeFromGMT(String dateTimePattern, String dateTimeGMT) {
try {
DateFormat utcFormat = new SimpleDateFormat(dateTimePattern);
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // convert from GMT TimeZone
Date date = utcFormat.parse(dateTimeGMT);
DateFormat deviceFormat = new SimpleDateFormat(dateTimePattern);
deviceFormat.setTimeZone(TimeZone.getDefault()); // Device TimeZone
return deviceFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
用法:
getDeviceDateTimeFromGMT("yyyy-MM-dd HH:mm", "2019-02-22 16:07");
getDeviceDateTimeFromGMT("yyyy-MM-dd HH:mm:ss", "2019-02-22 16:07:13");
getDeviceDateTimeFromGMT("H:mm", "16:07");