如何通过Flutter中的OpenWeather API使用时区属性获取任何城市/国家的当前时间?

问题描述

我通过使用OpenWeather的API得到了这个JSON响应:

{
"coord": {
"lon": 139.69,"lat": 35.69
},"weather": [
{
"id": 803,"main": "Clouds","description": "broken clouds","icon": "04d"
}
],"base": "stations","main": {
"temp": 306.63,"feels_like": 311.16,"temp_min": 304.82,"temp_max": 308.15,"pressure": 1011,"humidity": 63
},"visibility": 10000,"wind": {
"speed": 3.1,"deg": 140
},"clouds": {
"all": 75
},"dt": 1598419499,"sys": {
"type": 1,"id": 8077,"country": "JP","sunrise": 1598386129,"sunset": 1598433465
},"timezone": 32400,"id": 1850144,"name": "Tokyo","cod": 200
}

我希望使用timezone属性或其他属性获取该城市的当前时间。可能吗?怎么样?

解决方法

使用从API获取的timezone获取城市当前时间的方法如下:

DateTime.now().add(Duration(seconds: timezone - DateTime.now().timeZoneOffset.inSeconds))

您将从此处获得一个DateTime对象。

,

要解决您的问题,您必须将国家代码转换为国家名称,然后执行JSON代码来解决您的问题。

 TextView textView = findViewById(R.id.textView);

    Locale loc = new Locale("","JP");
    String country = loc.getDisplayCountry();

    //JSON Code

    TimeZone tz = TimeZone.getTimeZone(country + "/" + city);