Nothing earth-shattering, but may save you a few lines of code here and there.
NSDate-Misc.h
NSDate-Misc.m
#import <Foundation/Foundation.h>
@interface NSDate(Misc)
+ (NSDate *)dateWithoutTime;
- (NSDate *)dateByAddingDays:(NSInteger)numDays;
- (NSDate *)dateAsDateWithoutTime;
- (int)differenceInDaysTo:(NSDate *)toDate;
- (NSString *)formattedDateString;
- (NSString *)formattedStringUsingFormat:(NSString *)dateFormat;
@end
#import "NSDate-Misc.h"
@implementation NSDate(Misc)
+ (NSDate *)dateWithoutTime
{
return [[NSDate date] dateAsDateWithoutTime];
}
-(NSDate *)dateByAddingDays:(NSInteger)numDays
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:numDays];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:self options:0];
[comps release];
[gregorian release];
return date;
}
- (NSDate *)dateAsDateWithoutTime
{
NSString *formattedString = [self formattedDateString];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM dd, yyyy"];
NSDate *ret = [formatter dateFromString:formattedString];
[formatter release];
return ret;
}
- (int)differenceInDaysTo:(NSDate *)toDate
{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSDayCalendarUnit
fromDate:self
toDate:toDate
options:0];
NSInteger days = [components day];
[gregorian release];
return days;
}
- (NSString *)formattedDateString
{
return [self formattedStringUsingFormat:@"MMM dd, yyyy"];
}
- (NSString *)formattedStringUsingFormat:(NSString *)dateFormat
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:dateFormat];
NSString *ret = [formatter stringFromDate:self];
[formatter release];
return ret;
}
@end
Posted in: Categories,Cocoa,Cocoa Touch,NSDate
Kirimkan Ini lewat Email
BlogThis!
Bagikan ke X
Berbagi ke Facebook
0 komentar:
Posting Komentar