将当前时间(dt)从秒转换为实时格式(小时和分钟) [英] Convert current time(dt) from seconds to real time format(hour and minute)
问题描述
我能够使用来自 JSON 响应的改造在我的应用程序上显示一些天气数据,但当前时间 (dt)、日出和日落在我的文本视图上显示为秒,即 1612730263.所以我需要将时间转换为实时格式(小时和分钟),例如晚上 9:30.免责声明:Java:来自 unix 时间戳的日期 和 如何将秒转换为时间格式? 对我不起作用,因为我的响应来自 API.因此我的问题不是重复的.
I was able to display some weather data on my app using retrofit from a JSON response, but the current time(dt), sunrise, and sunset displays on my textviews as seconds i.e 1612730263. So I need to convert the time to a real-time format(hour and minute) e.g 9:30 PM. Disclaimer: Java: Date from unix timestamp and How to convert seconds to time format? doesn't work for me because my response is from an API. Therefore my question is not a duplicate.
我的 API 响应:
{
"lat":9.0765,
"lon":7.3986,
"timezone":"Africa/Lagos",
"timezone_offset":3600,
"current":{
"dt":1612779720,
"sunrise":1612763455,
"sunset":1612805901,
"temp":304.15,
"feels_like":302.14,
"pressure":1013,
"humidity":33,
"dew_point":286,
"uvi":8.42,
"clouds":42,
"visibility":7000,
"wind_speed":4.12,
"wind_deg":100,
"weather":[
{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03d"
}
]
}
}
我在 HomeActivity 中的 Retrofit 调用:
My Retrofit call for the time in HomeActivity:
Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrl).addConverterFactory(GsonConverterFactory.create()).build();
WeatherService service = retrofit.create(WeatherService.class);
Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, AppId);
call.enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(@NonNull Call<WeatherResponse> call, @NonNull Response<WeatherResponse> response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
assert weatherResponse != null;
assert response.body() != null;
// current time textview
time_field.setText(String.valueOf(response.body().getCurrent().getDt()));
我的 Retrofit 号召时间 &在 FirstFragment 中:
My Retrofit call for the time & in FirstFragment:
Retrofit retrofit = new Retrofit.Builder().baseUrl(BaseUrl).addConverterFactory(GsonConverterFactory.create()).build();
WeatherService service = retrofit.create(WeatherService.class);
Call<WeatherResponse> call = service.getCurrentWeatherData(lat, lon, AppId);
call.enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(@NonNull Call<WeatherResponse> call, @NonNull Response<WeatherResponse> response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = response.body();
assert weatherResponse != null;
assert response.body() != null;
// sunrise & sunset time textviews
rise_time.setText(response.body().getCurrent().getSunrise() + " AM");
set_time.setText(response.body().getCurrent().getSunset() + " PM");
编辑
WeatherResponse.java:
public class WeatherResponse {
@SerializedName("lat")
@Expose
private Double lat;
@SerializedName("lon")
@Expose
private Double lon;
@SerializedName("timezone")
@Expose
private String timezone;
@SerializedName("timezone_offset")
@Expose
private Integer timezoneOffset;
@SerializedName("current")
@Expose
private Current current;
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public Integer getTimezoneOffset() {
return timezoneOffset;
}
public void setTimezoneOffset(Integer timezoneOffset) {
this.timezoneOffset = timezoneOffset;
}
public Current getCurrent() {
return current;
}
public void setCurrent(Current current) {
this.current = current;
}
}
Current.java:
public class Current {
@SerializedName("dt")
@Expose
private Integer dt;
@SerializedName("sunrise")
@Expose
private Integer sunrise;
@SerializedName("sunset")
@Expose
private Integer sunset;
@SerializedName("temp")
@Expose
private Double temp;
@SerializedName("feels_like")
@Expose
private Double feelsLike;
@SerializedName("pressure")
@Expose
private Integer pressure;
@SerializedName("humidity")
@Expose
private Integer humidity;
@SerializedName("dew_point")
@Expose
private Double dewPoint;
@SerializedName("uvi")
@Expose
private Double uvi;
@SerializedName("clouds")
@Expose
private Integer clouds;
@SerializedName("visibility")
@Expose
private Integer visibility;
@SerializedName("wind_speed")
@Expose
private Double windSpeed;
@SerializedName("wind_deg")
@Expose
private Integer windDeg;
@SerializedName("weather")
@Expose
private List<Weather> weather = null;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public Integer getSunrise() {
return sunrise;
}
public void setSunrise(Integer sunrise) {
this.sunrise = sunrise;
}
public Integer getSunset() {
return sunset;
}
public void setSunset(Integer sunset) {
this.sunset = sunset;
}
public Double getTemp() {
return temp;
}
public void setTemp(Double temp) {
this.temp = temp;
}
public Double getFeelsLike() {
return feelsLike;
}
public void setFeelsLike(Double feelsLike) {
this.feelsLike = feelsLike;
}
public Integer getPressure() {
return pressure;
}
public void setPressure(Integer pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public Double getDewPoint() {
return dewPoint;
}
public void setDewPoint(Double dewPoint) {
this.dewPoint = dewPoint;
}
public Double getUvi() {
return uvi;
}
public void setUvi(Double uvi) {
this.uvi = uvi;
}
public Integer getClouds() {
return clouds;
}
public void setClouds(Integer clouds) {
this.clouds = clouds;
}
public Integer getVisibility() {
return visibility;
}
public void setVisibility(Integer visibility) {
this.visibility = visibility;
}
public Double getWindSpeed() {
return windSpeed;
}
public void setWindSpeed(Double windSpeed) {
this.windSpeed = windSpeed;
}
public Integer getWindDeg() {
return windDeg;
}
public void setWindDeg(Integer windDeg) {
this.windDeg = windDeg;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
}
请我需要提供的代码链接到我的应用程序,以便更容易实现它.我有 dt 转换的基本知识,但不了解天气 API 响应.我认为使用我的文本视图来转换数据会更好(如果有任何方法可以使用我的文本视图来完成)
Please I need the code provided to be linked to my app so that it will be easier to implement it. I have basic knowledge of dt conversion, but not from a weather API response. I think using my textviews to convert the data will be better(If there's any way you can use my textviews to do it)
推荐答案
看来您需要从 WeatherResponse
和相关类中返回的信息中获取正确的日期模式.
It seems you need to obtain the right date patterns right from the information returned in the WeatherResponse
and related classes.
为此,您需要自定义您在代码中使用的 Gson 库,以反序列化由 Retrofit 提供的 openweathermap API 返回的信息.
For this purpose, you need to customize the Gson library you are using in your code to deserialize the information returned by the openweathermap API by Retrofit.
有几种方法可以做到这一点,但只要您有能力修改由 jsonschema2pojo
生成的类,我建议采用以下方法.
There are several ways to do this but, as far as you have the ability to modify the classes generated by jsonschema2pojo
, I would suggest the following approach.
这个想法基本上包括实现一个自定义Gson解串器来处理所需的转换.
The idea consists basically in implement a custom Gson deserializer to handle the required transformation.
您可以选择为整个 Current
类实现这个自定义反序列化器,但我认为只处理必要字段的反序列化会更容易.
You can opt for implement this custom deserializer for the whole Current
class but I think it will be easier to only handle the deserialization of the necessary fields.
为此,首先,让我们创建一个新类型;它将作为需要自定义反序列化的字段的标记.例如:
For that purpose, first, let's create a new type; it will serve as a marker for the fields that require the custom deserialization. For example:
public class PrettyTime {
private String value;
public PrettyTime() {
}
public PrettyTime(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return getValue();
}
}
将此标记应用于Current
类中需要转换的字段:
Apply this marker to the fields you need the conversion in the Current
class:
public class Current {
@SerializedName("dt")
@Expose
private PrettyTime dt;
@SerializedName("sunrise")
@Expose
private PrettyTime sunrise;
@SerializedName("sunset")
@Expose
private PrettyTime sunset;
// The rest of the fields and setters and getters
public PrettyTime getDt() {
return dt;
}
public void setDt(PrettyTime dt) {
this.dt = dt;
}
public PrettyTime getSunrise() {
return sunrise;
}
public void setSunrise(PrettyTime sunrise) {
this.sunrise = sunrise;
}
public PrettyTime getSunset() {
return sunset;
}
public void setSunset(PrettyTime sunset) {
this.sunset = sunset;
}
}
接下来,让我们创建自定义解串器:
Next, let's create the custom deserializer:
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PrettyTimeDeserializer implements JsonDeserializer<PrettyTime> {
// Modify the date pattern as you consider appropriate
private static final SimpleDateFormat HMM = new SimpleDateFormat("hh:mm");
public PrettyTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
final long seconds = json.getAsJsonPrimitive().getAsLong();
final Date date = new Date(seconds * 1000);
final String prettyFormatted = HMM.format(date);
return new PrettyTime(prettyFormatted);
}
}
最后,将此反序列化器集成到您的代码中,包括 HomeActivity
和 FirstFragment
类:
Finally, integrate this deserializer in your code, both in the HomeActivity
and FirstFragment
classes:
Gson gson = new GsonBuilder()
.registerTypeAdapter(PrettyTime.class, new PrettyTimeDeserializer())
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
// Please note the gson argument
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
;
// The rest of your code
这篇关于将当前时间(dt)从秒转换为实时格式(小时和分钟)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!