views:

146

answers:

3

Hi guys, I've got two NSDate, date and time. I'd like to add them in such a manner that I get the date from date and time from time. Any suggestions on how I do this?

Cheers

Nik

+1  A: 

If I got you right NSDates -dateByAddingTimeInterval: together with -timeIntervalSinceDate: are what you looking for.

hth
–f

flohei
+1  A: 

Use NSCalendars components:fromDate: to get the components of the two dates.
Then reassemble them as needed using dateFromComponents:.

Georg Fritzsche
Thanks, this worked beautifully :-)
niklassaers
+1  A: 

I've got two NSDate, date and time.

Sounds like you're going about it wrong.

An NSDate represents a specific moment in time (X seconds since the epoch). An NSDate is not simply “x o'clock” or “this date on the calendar”, and you shouldn't attempt to combine them as if they were because effects such as DST may make your computation wrong (in some time zones, some dates have two 1:00 hours, and some have no 2:00 hours).

Consider using an NSDatePicker or UIDatePicker (as appropriate) to let the user enter the date and time from a single place. Not only is this easier for you to do, it'll also give more correct results.

If you're reading the two pieces separately from a file or similar source, and you don't control the format (so you can't order the generating side to emit dates with their times in one value), you'll need to do one of two things:

  • If possible, combine the two strings. For example, an ISO 8601 date (e.g., “2010-05-10”) and an ISO 8601 time (e.g., “23:20:19-0700”) can be concatenated with a ‘T’ between them to form a valid, fully-specified ISO 8601 date (“2010-05-10T23:20:19-0700”). You can then pass this single string to a properly-configured NSDateFormatter.

  • If, for some reason, you can't combine the strings meaningfully, parse them yourself and fill out a single NSDateComponents object yourself.

    This will not be pleasant, but correctness is important, and a bug (incorrect date parsing) that only happens in two hours out of every year for only some of your users will be maddening.

The goal is to produce exactly one NSDate object that completely describes the date and time in question. This is the only way to ensure that, in all circumstances, you get the correct NSDate value.

Peter Hosey