【问题标题】:Regading about JSON data parsing in Android关于Android中的JSON数据解析
【发布时间】:2016-03-13 07:30:16
【问题描述】:

我正在使用 openweather API 来调用当前位置。在 JSON 解析中,我看到 "dt": 1457852143 (UTC/unix) http://openweathermap.org/weather-data 这意味着最后更新。所以在我的应用程序中,我将该值存储在字符串变量 String last_update=total.getString("dt")总共保存了完整的 JSON 数据。我运行了我的应用程序并在屏幕上得到了 1457852143 的输出。虽然我希望它在本地时间显示,但我无法转换。 我正在使用 Android Studio 1.5。任何建议将不胜感激。

【问题讨论】:

  • 请更清楚地说明您已经尝试过哪些不起作用。您可以通过this 了解如何在这个社区提出问题。
  • 1457852143 将其转换为 UTC unix。这是一毫秒的时间。这与 FireBase 的时间戳相同。
  • Aizen,是的,我知道它是 UTC,但我无法将其格式化为本地时区。你能帮我解决这个问题吗?

标签: android json android-studio


【解决方案1】:

我以前使用过以下方法来执行此操作。这是使用 Date 类,但我听说最好使用 Calendar 类。不过,这应该会让您朝着正确的方向前进。

    public static String convertUTCtoLocalTime(String p_city, String p_UTCDateTime) throws Exception{

String lv_dateFormateInLocalTimeZone="";//Will hold the final converted date
Datelv_localDate = null;
Stringlv_localTimeZone ="";
SimpleDateFormat lv_formatter;
SimpleDateFormat lv_parser;

//Temp for testing(mapping of cities and timezones will eventually be in a properties file
if(p_city.equals("LON")){
lv_localTimeZone="Europe/London";
}else if(p_city.equals("NBI")){
lv_localTimeZone="EAT";
}else if(p_city.equals("BRS")){
lv_localTimeZone="Europe/Brussels";
}else if(p_city.equals("MNT")){
lv_localTimeZone="America/Montreal";
}else if(p_city.equals("LAS")){
lv_localTimeZone="PST";}

//create a new Date object using the UTC timezone
lv_parser = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
lv_parser.setTimeZone(TimeZone.getTimeZone("UTC"));
lv_localDate = lv_parser.parse(p_UTCDateTime);

//Set output format - // prints "2007/10/25  18:35:07 EDT(-0400)"
lv_formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z'('Z')'");
System.out.println("convertUTCtoLocalTime "+p_city+": "+ "The Date in the UTC time zone(UTC) " + lv_formatter.format(lv_localDate));

//Convert the UTC date to Local timezone
lv_formatter.setTimeZone(TimeZone.getTimeZone(lv_localTimeZone));
lv_dateFormateInLocalTimeZone = lv_formatter.format(lv_localDate);
System.out.println("convertUTCtoLocalTime: "+p_city+": "+"The Date in the LocalTime Zone time zone " + lv_formatter.format(lv_localDate));

return lv_dateFormateInLocalTimeZone;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多