27

I'm launching an activity and would like to pass a Date(Time) value to it. I've passed all my other parameters with i.putExtra("noteName", "Hello World") but I'm clueless on how to pass the date value and then retrieve it as a date with getExtra().

I can easily use i.putExtra("noteDate",noteDate);

but then how do i retrieve it in the Activity's onCreate(); I don't see an extras.getDate() ?

Should I convert it to Float and then back (in the Activity)?

Thanks

MPelletier
  • 16,256
  • 15
  • 86
  • 137
Hein du Plessis
  • 3,305
  • 6
  • 34
  • 51

4 Answers4

49

Use date.getTime() and date.setTime() and transfer it as a Long.

i.putExtra("date", date.getTime());

Date d = new Date();
d.setTime(i.getLongExtra("date", -1));
Robby Pond
  • 73,164
  • 16
  • 126
  • 119
  • Thanks, but I'm having trouble with this, my date returns 1 Jan 1970 no matter what I do. – Hein du Plessis Mar 21 '11 at 20:40
  • check to see what i.getLongExtra() is returning, it returns a -1 if "date" is not in the extras. – Robby Pond Mar 21 '11 at 20:43
  • yes It's -1, but if I do a i.putExtra("noteDate", noteDate.toString()); I can extras.getString("noteDate")); and the value comes through. If I put it as a date and use getIntent.getLongExtra("noteDate",-1)) i get back -1 ? – Hein du Plessis Mar 21 '11 at 20:49
4

better convert into a long, use putExtra(String name, long value) and recreate then back in the new Activity.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
Franco
  • 7,385
  • 3
  • 27
  • 22
  • 1
    Sorry, I'm really new to java, could you explain how to do Date > Long and back? – Hein du Plessis Mar 21 '11 at 20:41
  • 2
    long millis = [date.getTime()](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime()); <--> Date date = [new Date(millis)](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#Date(long)); – naXa stands with Ukraine May 29 '14 at 13:53
2

I've simply used

i.putExtra("noteDate",myDate);

and then on the activity I used:

Date dt = new Date(extras.getString("noteDate"));

and it works like a charm!? Is this dangerous? To assume the date will always be parsed correctly on all devices?

Hein du Plessis
  • 3,305
  • 6
  • 34
  • 51
1

Instead of

i.putExtra("date", date.getTime());
Date d = new Date();
d.setTime(i.getLongExtra("date", -1));

USE : if you are using Calendar instead of Date to get the long value

i.putExtra("date", date.getTime().getTime); 
Date d = new Date();
d.setTime(i.getLongExtra("date", -1));
Raghu Vallikkat
  • 365
  • 5
  • 16