I am trying to convert the millisecond format of time provided by openweathermap but when I convert them the times are just 1minute apart.
I have tried converting using Simpledateformat
.
fun formatTIme(sun:Date):String{
val timeformat:SimpleDateFormat= SimpleDateFormat("h:m a")
return timeformat.format(sun)
}
sys": {
"type": 1,
"id": 9201,
"message": 0.0075,
"country": "NP",
"sunrise": 1571444437,
"sunset": 1571485599
},
"timezone": 20700,
"id": 1282682,
"name": "Thapathali",
"cod": 200
}
API call is done through Nepal
if this helps.
Why the time is just 1min difference?
Can anyone help me
I am sorry that I can write only Java code. I trust you to translate. For demonstration I am using this snippet.
long sunrise = 1571444437;
long sunset = 1571485599;
System.out.println(formatTime(Instant.ofEpochSecond(sunrise)));
System.out.println(formatTime(Instant.ofEpochSecond(sunset)));
Output is:
6:05 AM 5:31 PM
I have declared formatTime
like this — and it works on your API level, see the details below.
static final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("h:mm a", Locale.ENGLISH)
.withZone(ZoneId.of("Asia/Kathmandu"));
static String formatTime(Instant time) {
return formatter.format(time);
}
I have specified two-digit minutes to obtain 6:05
, which is customary rather than 6:5
. If you prefer the latter, change mm
to just m
in the format pattern string. If you want AM
and PM
this way, as is customary in English, it’s a good idea to specify English locale.
Multiplying the seconds since the epoch by 1000 to obtain milliseconds, as suggested in the comments, works, but doing your own time conversions like this is a bad habit. While multiplying by 1000 seems simple, it may already leave the person reading your code wondering, and such conversions get complicated and error-prone very quickly. We have well-proven library methods to do them, which also leaves our code self-documenting: my use of the ofEpochSecond
method already says that the number is in seconds, and there is no need for wondering, everything is clear, I think.
If you are not yet on Android API level 26 and you don’t want an external dependency, use the following for conversion:
TimeUnit.SECONDS.toMillis(sunrise)
This also tells the reader more clearly that you are doing a conversion from seconds to milliseconds.
You haven’t shown the code where it goes wrong, but I think it’s clear from the comments. When treating your seconds since the epoch as milliseconds, you get 1970-01-19T10:00:44.437+05:30[Asia/Kathmandu]
for sunrise and 1970-01-19T10:01:25.599+05:30[Asia/Kathmandu]
for sunset. As you noted, there is less than a minute between them.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).