faqts : Computers : Programming : Application Frameworks : Macintosh : Cocoa

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 2 people (100%) answered Yes
Recently 2 of 2 people (100%) answered Yes

Entry

How can I convert an UTCDateTime to a NSDate?

Apr 29th, 2002 19:39
Christopher Holland, Rainer Brockerhoff


This is what I use:
NSDate* dateForJan1904() {		// utility to return a singleton reference NSDate
	static NSDate* Jan1904 = nil;
	if (!Jan1904) {
		Jan1904 = [[NSDate dateWithString:@"1904-01-01 00:00:00 +0000"] retain];
	}
	return Jan1904;
}
NSDate* convertUTCtoNSDate(UTCDateTime input) {
	NSDate* result = nil;
	union {
		UTCDateTime local;
		UInt64 shifted;
	} time;
	time.local = input;
	if (time.shifted) {
		result = [[[NSDate alloc] initWithTimeInterval:time.shifted/65536
			sinceDate:dateForJan1904()] autorelease];
	}
	return result;
}
It returns an autoreleased NSDate, or nil if the input value was zero.
It rounds fractional seconds down. I suppose you could gain a couple 
of cycles by doing some back&forth casting on the input, but I find 
this more legible...
Conversely, here's the NSDate to UTCDateTime routine:
UTCDateTime convertNSDatetoUTC(NSDate* date) {
	union {
		UTCDateTime local;
		UInt64 shifted;
	} result;
	result.shifted = date?[date timeIntervalSinceDate: dateForJan1904()]*65536:0;
	return result.local;
}