TwitterCounter for @bigclick_dean

dBlog.com.au

My Development Blog

Well I needed a way to get a formatted date string in NSString format so I dug around and came up with the following function.

-(NSString *) dateInFormat:(NSString*) stringFormat {
	char buffer[80];
	const char *format = [stringFormat UTF8String];
	time_t rawtime;
	struct tm * timeinfo;
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	strftime(buffer, 80, format, timeinfo);
	return [NSString  stringWithCString:buffer encoding:NSUTF8StringEncoding];
}

What it does it it takes a NSString as input with set specifications (checkout http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/strftime.3.html for the full list of specifications) and it returns the compiled date string as a NSString ready for you to use.

It is pretty much just a wrapper for the C strftime function but I thought it would be helpful to share as you often need dates or times in games/applications.

Here are some usage examples and their expected outputs:

[self dateInFormat:@"%s"] // Should return a UNIX timestamp, i.e. "1222738875"

[self dateInFormat:@"Today is %A"] // Should return "Today is Tuesday"

[self dateInFormat:@"%+"] // Should return "Tue Sep 30 11:50:01 EST 2008"

[self dateInFormat:@"%Z (%z)"] // Should return timezone + UTC offset in brackets, i.e. "EST (+1000)"

[self dateInFormat:@"%Y-%m-%d-%H:%M:%S"] // Should return a date/time stamp as used my many programs (MySQL, PHP, etc) i.e. 2008-09-30-11:54:03
NOTE: You can also use [self dateInFormat:@"%Y-%m-%d-%X"] to get the same result as above.

I hope that this function will be able to same someone 5-10 minutes as I know I will be using it for a few of my projects.

Popularity: 2% [?]

Comments

There are 2 comments for this post.

  1. Michelle on March 11, 2009 3:37 pm

    I’m not sure what exact set of formats you need, but could you not use NSDateFormatter for most of them?

  2. Balius on March 19, 2009 3:35 pm

    Typo: You mean “save people 5-10 minutes…” lol

    B

Trackbacks

  • There are no trackbacks for this post

Write a Comment