My weather App displays Datetime(last updated), Sunrise, and Sunset data from OpenWeatherMap in the form of milliseconds(i.e 1620792785). I'm trying to convert it to a real-time format (i.e hh:mm a).
So I want to:
- Convert the dt accurately
- Convert Sunrise and Sunset time accurately using the right codes and classes.
My app can search for any city, so I'm not getting for a particular timezone but for all cities.
My Example class: (for dt, sunrise & sunset specifically)
public class Example {
@SerializedName("dt")
private Integer dt;
public Integer getDt() {
return dt;
}
public void setDt(Integer dt) {
this.dt = dt;
}
public class Coord {
@SerializedName("lon")
private Double lon;
@SerializedName("lat")
private Double lat;
public Double getLon() {
return lon;
}
public void setLon(Double lon) {
this.lon = lon;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
}
public class Sys {
@SerializedName("sunrise")
private Integer sunrise;
@SerializedName("sunset")
private Integer sunset;
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 String getPrettyDate() {
SimpleDateFormat HMM = new SimpleDateFormat("hh:mm a", Locale.US);
final Date date = new Date(dt*1000);
return HMM.format(date);
}
}
My Activity class(Where I called dt):
time_field.setText("Last Updated:" + " " + response.body().getPrettyDate());
My FirstFragment class(Where I called sunrise and sunset):
rise_time.setText(response.body().getSys().getSunrise() + " ");
set_time.setText(response.body().getSys().getSunset() + " ");
What I have tried:
I tried using this code for dt in my example class:
public String getPrettyDate() {
SimpleDateFormat HMM = new SimpleDateFormat("hh:mm a", Locale.US);
final Date date = new Date(dt*1000);
return HMM.format(date);
}
Then called
time_field.setText("Last Updated:" + " " + response.body().getPrettyDate());
from my Activity class. It converted the time well, but it didn't display the data accurately(i.e when it was 3 pm here, it showed 9 pm).
I also tried using this:
public static String toDate(int time) {
SimpleDateFormat HMM = new SimpleDateFormat("hh:mm a");
HMM.setTimeZone(TimeZone.getTimeZone("UTC"));
final Date date = new Date(time*1000);
return HMM.format(date);
}
for my sunrise and sunset.
Then called
rise_time.setText(todate(response.body().getSys().getSunrise() + " "));
set_time.setText(todate(response.body().getSys().getSunset() + " "));
In my fragment class, but it gave an error suggesting to change int to string.
I as well asked it on StackOverflow
java - Convert Datetime, Sunrise and Sunset from miliseconds to real time format - Stack Overflow[
^] , but It got termed as duplicate when it's not and removed.