Wednesday, September 30, 2009

Can I get a date?

NSDate


I'm pretty sure this is not the official way to do it, but an easy way to extract the year-month-date information from an NSDate instance is to do

componentsSeparatedByString:@" "

on the description. Also, notice that constructing an NSDate object from a string requires a complete specification---including the time zone!

And at first I thought, there seems to be a bug in Apple's implementation of the dateWithString method. We specified January 1, but the resulting NSDate is one day (and one year) earlier. The answer lies in the time zone. Cocoa has converted my GMT time in constructing the NSDate to the current time zone where I am, even correcting for daylight savings time on the appropriate dates.

today 2009-09-30 16:05:32 -0400
array a (
"2009-09-30",
"16:05:32",
"-0400"
)
array b (
2009,
09,
30
)
birthday 2000-12-31 19:00:00 -0500
present age (seconds) 276033932.002803
age doubled 2018-06-30 12:11:04 -0400
age halved 2005-05-17 06:02:46 -0400



// gcc -o test test3.m -framework Foundation -fobjc-gc-only
// ./test
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
//NSCalendarDate is deprecated
NSDate *today = [NSDate date];
NSLog(@"today %@", [today description]);
NSArray *a = [[today description]
componentsSeparatedByString:@" "];
NSArray *b = [[a objectAtIndex:0]
componentsSeparatedByString:@"-"];
NSLog(@"array a %@", a);
NSLog(@"array b %@", b);

// creating a date from a string
// requires all the pieces!

NSString *s = @"2001-01-01 00:00:00 +0000";
NSDate *bd = [NSDate dateWithString:s];
NSLog(@"birthday %@", [bd description]);

NSTimeInterval ti = [today
timeIntervalSinceDate:bd];
// it is wrong to use d here!
NSLog(@"present age (seconds) %f", ti);

// OS X 10.6 only
NSDate *ageDoubled = [NSDate dateWithTimeInterval:ti
sinceDate:[NSDate date]];
NSLog(@"age doubled %@", ageDoubled);
NSDate *ageHalved = [NSDate dateWithTimeInterval:(ti/2)
sinceDate:bd];
NSLog(@"age halved %@", ageHalved);
return 0;
}