views:

1910

answers:

4

I would like to subtract 4 hours from a date. I read the date string into an NSDate object use the following code:

NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate * mydate = [dateFormatter dateFromString:[dict objectForKey:@"published"]];

What do I do next?

+5  A: 

NSCalendar is the general API for changing dates based on human time units. For this, you can use NSCalendar's -dateByAddingComponents:toDate:options: with a negative number of hours.

Chuck
This is a much better approach--it deals with DST, leap years, all that.
drewh
NSCalendar is not a recommended API to use. http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendarDate_Class/Reference/Reference.html
norskben
@norskben: That page is for NSCalendar**Date**. That's what it says not to use. It specifically recommends NSCalendar as a replacement in the same note.
Chuck
+1  A: 
NSDate *newDate = [theDate addTimeInterval:-3600*4];

Link to documentation.

Strange that this method returns a new NSDate object, it completely differs from the naming conventions. I wonder if the returned date is autoreleased, probably yes.


NSDate *newDate = [[[NSDate alloc] initWithTimeInterval:-3600*4
                                              sinceDate:theDate]] autorelease];

Link to documentation.

Georg
+1  A: 

Still not working.... what am I doing wrong?

NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSString * datetemp = [dict objectForKey:@"published"];
NSString * theDate = [dateFormatter dateFromString:datetemp];
NSDate *newDate = [theDate addTimeInterval:-3600*4];
self.dateLabel.text = newDate;
Miriam Roberts
Update your question, don't just post your update as an answer.
`self.dataLabel.text` is an NSString, but you're setting it to an `NSDate`. For a quick-and-dirty hack, try `self.dateLabel.text = [newDate description];` (for cleaner, use an date formatter to format the date the way you like).
Daniel Dickison
I had to remove the 'Z' and other chars from the date before it would format properly.
Miriam Roberts
+1  A: 

Hey Miriam,
dateFromString function returns NSDate, not NSString. you should change,

NSDate * theDate = [dateFormatter dateFromString:datetemp];

hope it helps,
bests.
G.

Guvener Gokce