Every repository with this icon (
Every repository with this icon (
| name | age | message | |
|---|---|---|---|
| |
NSDate+Helper.h | Thu Dec 03 06:56:42 -0800 2009 | |
| |
NSDate+Helper.m | Thu Dec 03 06:56:42 -0800 2009 | |
| |
README.textile | Mon Nov 16 07:10:34 -0800 2009 |
NSDate (Helper)
This is a category for the NSDate class that provides some convenience methods for working with NSDate objects and displaying formatted and relative strings.
More information can be found at my initial blog post.
Anyone is welcome to use it for anything, and to change it as they see fit. If you’d like to contribute back any changes (woot!), please fork and send a pull request!
Usage
Full documentation is now up on the Github wiki for this project. It’s a lot better than this kinda rambling overview here.
Two convenience methods make it easy for you to display some relative date information. stringForDisplayFromDate gives you the kind of relative format you see in the Notes listing on the iPhone:
NSString *displayString = [NSDate stringForDisplayFromDate:date];
This produces the following kinds of output:
- ‘3:42 AM’ – if the date is after midnight today
- ‘Tuesday’ – if the date is within the last seven days
- ‘Mar 1’ – if the date is within the current calendar year
- ‘Mar 1, 2008’ – else ;-)
NSString *displayString = [NSDate stringForDisplayFromData:date prefixed:YES];
This produces the same as above, but prefixed with ‘at’ or ‘on’ depending on the appropriate English syntax.
Another set of methods provide days-ago information:
NSDate *date = [NSDate date];
[date daysAgo]; // provides an NSComponent-based NSUInteger describing days ago.
[date daysAgoAgainstMidnight]; // better version of daysAgo, works off midnight (hat-tip: "sburlot":http://github.com/sburlot)
[date stringDaysAgo]; // 'Today', 'Yesterday', or 'N days ago'.
Tired of creating and releasing date formatters? Missing things like to_s(:db)? Me, too. NSDate (Helper) has some static methods to make going back and forth between strings and dates a little less painful, and particularly easier when working with database timestamps (a la SQLite):
NSDate *date = [NSDate dateFromString:@"2009-03-01 12:15:23"];
NSString *dbDateString = [NSDate stringFromDate:date]; // returns '2009-03-01 12:15:23'
Who needs NSDateFormatter?
NSString *otherDateString = [NSDate stringFromDate:date withFormat:@"EEEE"]; // use any format you likeInstallation
To use it in your Cocoa project, import the header and implementation files, and then add the header to your project’s _prefix.pch file so that it’s available across your project:
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "NSDate+Helper.h"
#endif







