【问题标题】:How to convert time as per Timezone selection in android?如何根据android中的时区选择转换时间?
【发布时间】:2017-03-30 08:51:12
【问题描述】:

我的应用程序正在下载购物详情。
例子 : 购物详情于伦敦时间 5 :30 下载。
现在,更改任何其他时区,因此根据所选时区转换下载时间。
时区正在从日期/时间下的设置更改。 如何以编程方式实现这一目标? 那么如何根据时区选择转换下载的时间

【问题讨论】:

  • TimeZone.getDefault() 将为您提供设备时区。
  • @Raghvendra :好的,它会给我当前时区,现在将已下载的时间转换为该时区选择。那是怎么计算的呢?
  • 你能把你下载的示例时间贴出来吗?我是指当时的格式。?
  • @Raghvendra - 例如时间 = 下载时间 = 08:15 - 根据伦敦时区,现在选择 IST 时区,因此现在 (GMT + 5:30) 应该转换时间。那么这怎么能在这里实现呢?
  • @Swift 你是如何做到这一点的,我有同样的要求,你能发布你的答案吗?

标签: android datetime android-studio timezone android-timepicker


【解决方案1】:

不,没有用于更改时间或时区的 API。无法以编程方式更改手机的时区。

【讨论】:

  • 不,我在问。是否有任何代码 sn-p 我们可以在哪里获取设备的当前时区并根据时区选择转换下载时间?
【解决方案2】:

试试这个,

我假设您已在伦敦时间下午 12:00 下载了购物详情。我使用 HH 假设您使用的是 24 小时格式。如果要将其转换为设备默认时区,请使用 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){

}

【讨论】:

  • 谢谢,现在有用了。
  • @Swift 很高兴!这有帮助:)
【解决方案3】:

基于@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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2012-07-24
    相关资源
    最近更新 更多