Source java.util.Date

I am trying to make one of my Parcelable classes, and one of its attributes is a Date object.

In the writeToParcel () method, I have:

out.writeLong(myDate.getTime()); 

And in my createFromParcel () method, I have

 person.setDate(new Date(in.readLong() * 1000)); 

The object that I pass to my intention has a date created as follows:

 new Date(2000,12,06) 

But, when I read it on the other hand, in another activity:

 myDate.getYear()+"-"+myDate.getMonth()+"-"+myDate.getDay() 

He prints "2001-0-0"

I assume that something is being wound up during the sending process?

+4
source share
2 answers

You write milliseconds from the Unix era (see the documentation for getTime() ).

The Date constructor, which takes a long value, takes milliseconds since the Unix era (see the documentation for this constructor ).

On the contrary, you go through microseconds from the Unix era for the constructor. Just pass the readLong() value to the Date constructor and see if that helps.

+3
source

Your mistake is how you create the Date object, see additional documentation.

Options

year, 0 - 1900 (for example, 100 - 2000).

month of the year, 0 - 11 (for example, June - 5).

day of the month, 1 - 31 (do not think that this is an example).

as you can see, when you do this β€œ new date (2000,12,06) ”, you do not create what you thought you were creating in the first place. It is also not recommended that the method be deprecated with API 1 , so please do not use it unless you are targeting API 1, which I don’t think anyone is doing this anymore.

Also, as CommonsWare reported, remove 1000 at the end when reading.

+1
source

Source: https://habr.com/ru/post/1486725/


All Articles