Click here to Skip to main content
14,927,127 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.
Posted
Updated 14-May-21 7:10am
v2
Comments
SeanChupas 14-May-21 12:35pm
   
This is how you simple down your question. You said, "Convert Sunrise and Sunset time accurately." OK, what format is sunrise in? You mentioned it might look like 1620792785. But what is that number? How would you convert it?

Once you answer that question all you have to do is write code to convert it. Very easy.
Chinedum Ezeozue 14-May-21 12:45pm
   
Both sunrise and sunset are not specific, that was why I gave an instance.

Like I said
My app can search for any city, so I'm not getting for a particular timezone but for all cities.
SeanChupas 14-May-21 12:50pm
   
But you haven't even answered my question. All you want to do is convert 1620792785 to an actual datetime, right? If not, what IS your question?

Because you are not being clear on what you need help with.
Chinedum Ezeozue 14-May-21 12:53pm
   
No your not understanding. I don't want to convert 1620792785, but any data the dt, sunrise and sunset returns whenever the user searches for a particular city.

But they always return instance like that. It's not specific since it's not only a city
SeanChupas 14-May-21 13:00pm
   
I know you don't want to convert that specific number to date time. But you want to convert sunrise to date time, right?
SeanChupas 14-May-21 13:02pm
   
I just looked at a sample response and they have:

"sunrise": 1560343627,
"sunset": 1560396563

So, YES, your question IS how to convert those numbers to date time, right?
SeanChupas 14-May-21 13:05pm
   
You have to know what those numbers mean. So, read the documentation and find out what they mean.
SeanChupas 14-May-21 13:06pm
   
The documentation is says it is in unix utc format. So, just google that to find out how to make sense of it. Seriously, we have been trying to help you over and over. Not sure why you are overcomplicating it.
Richard MacCutchan 14-May-21 12:40pm
   
If the time is off by some number of hours then you need to find out what it represents. Is it a UTC time value, or specific to some time zone?

"it gave an error suggesting to change int to string."
What was the exact error message, and which line of code caused it?
Chinedum Ezeozue 14-May-21 12:50pm
   
It's a UTC time value according to the documentation https://openweathermap.org/current

It just gave suggestion of either I change first parameter(int) to string or I use int parser. And it was because I made

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);
}

Static.
David Crow 15-May-21 11:51am
   
Have you tried something like:

Date dt(1620792785);
String s;
s.format("%02d:%02d", dt.getHour(), dt.getMinute());
Chinedum Ezeozue 15-May-21 13:57pm
   
Thanks, but I already fixed it using this solution: https://stackoverflow.com/a/66146060/15804753

   
Comments
Chinedum Ezeozue 14-May-21 11:00am
   
It's obvious, code project is a wrong place to look for answers. How can you show me documentation when I asked for help. How sad
Richard MacCutchan 14-May-21 11:35am
   
It would would have been easier if your question actually focused on the problem. all I could gathef (without struggling through those hundreds of lines of code) was that you want to convert a number of milliseconds into a DateTime. The link I provided shows how to do that - try studying it, or ask a clearer question.
Chinedum Ezeozue 14-May-21 11:43am
   
Sometimes, you have to post the code in order for the person helping you to actually fix the exact fault because you may give a solution to converting dt which may end up not corresponding with my app since they're many ways of doing it.

At least from what I've tried, you can show me a correction to that which may solve the issue.
Richard MacCutchan 14-May-21 11:47am
   
Well if you had just posted the code where the problem occurs, and explained in detail what the problem was, I may have been able to understand it. But there is no way I am going to be able to figure out from almost 600 lines of code.
Chinedum Ezeozue 14-May-21 11:55am
   
Oh k I'm sorry, I'll edit it and let you know
Chinedum Ezeozue 14-May-21 12:16pm
   
I've reduced it to the bare minimum
You are way overcomplicating this. All you need to do is convert the values in dt (and sunrise and sunset) to datetime.

Look at the documentation, it reads
Quote:
dt Time of data calculation, unix, UTC


So, all you have to do now is google "unix UTC to c# datetime" and the first result has the answer. From c# - How can I convert a Unix timestamp to DateTime and vice versa? - Stack Overflow[^]

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}


Very easy.
   
Comments
Chinedum Ezeozue 14-May-21 13:54pm
   
Okay. After converting this in my example class, how do I call it in my activity and fragment? Dt, sunrise & sunset section specifically?
SeanChupas 14-May-21 15:00pm
   
What do you mean how do you call it?
Chinedum Ezeozue 14-May-21 15:40pm
   
I called my getPrettyDate() in my fragment
time_field.setText("Last Updated:" + " " + response.body().getPrettyDate());
after

Converting in my example class.

How do I call this one? Or you mean just writing this code on the example class that way will fix it?
SeanChupas 14-May-21 16:17pm
   
I am not sure what you mean. I gave you code that will convert unix UTC to c# datetime. Where you put it and how you call it is up to you.
Chinedum Ezeozue 14-May-21 16:55pm
   
Exactly so you shouldn't have attempted to help me right from time when it's not from your heart because such code will always fail. I've told you my app is different and whether you help or not, I'll still find a solution at last. Don't do what's not from your heart please
SeanChupas 17-May-21 8:50am
   
I do not understand what you mean. You wanted to know how to convert dt into a datetime and I told you how to do that.

Whether you put that code into a function and call it or you do it inline, does not matter. That's up to you.
Chinedum Ezeozue 17-May-21 11:47am
   
Yeah, that's why I told you not to bother. I fixed it using a way much better method than the one you suggested
SeanChupas 17-May-21 12:04pm
   
There is no other method. That's how you convert it.

You are not being clear about anything, even when you are upset.
Chinedum Ezeozue 14-May-21 18:03pm
   
I just fixed it now using a custom deserializer. Don't even think not helping me will stop me from making it work
SeanChupas 17-May-21 12:03pm
   
You are being incredibly rude. I have helped you and others have tried. You are not very good at being clear with your question so we did the best we can.
Chinedum Ezeozue 17-May-21 12:17pm
   
You're more rude. I can never be rude to one who respects small young devs looking for help. You threw code at me and said "use it as you like, it's none of my business". Knowing fully well that I have difficulties understanding it myself
David Crow 15-May-21 11:48am
   
Just curious why searching for a C# solution would be suggested?
Chinedum Ezeozue 15-May-21 13:55pm
   
It was his idea and it was quite off point for my app
SeanChupas 17-May-21 8:49am
   
Because I misread the question. But finding java code is just as easy.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900