`

NSDate的分类方法(全)

阅读更多
自己新添加的一些NSDate的分类方法
////*****.m文件
#import "NSDate-Helper.h"
@implementation NSDate(Helpers)

/*
* This guy can be a little unreliable and produce unexpected results,
* you're better off using daysAgoAgainstMidnight
*/
//获取年月日如:19871127.
- (NSString *)getFormatYearMonthDay
{
NSString *string = [NSString stringWithFormat:@"%d%02d%02d",[self getYear],[self getMonth],[self getDay]];
return string;
}
//返回当前月一共有几周(可能为4,5,6)
- (int )getWeekNumOfMonth
{
return [[self endOfMonth] getWeekOfYear] - [[self beginningOfMonth] getWeekOfYear] + 1;
}
//该日期是该年的第几周
- (int )getWeekOfYear
{
int i;
int year = [self getYear];
NSDate *date = [self endOfWeek];
for (i = 1;[[date dateAfterDay:-7 * i] getYear] == year;i++)
{
}
return i;
}
//返回day天后的日期(若day为负数,则为|day|天前的日期)
- (NSDate *)dateAfterDay:(int)day
{
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
// NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
// to get the end of week for a particular date, add (7 - weekday) days
[componentsToAdd setDay:day];
NSDate *dateAfterDay = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
[componentsToAdd release];

return dateAfterDay;
}
//month个月后的日期
- (NSDate *)dateafterMonth:(int)month
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
[componentsToAdd setMonth:month];
NSDate *dateAfterMonth = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
[componentsToAdd release];

return dateAfterMonth;
}
//获取日
- (NSUInteger)getDay{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSDayCalendarUnit) fromDate:self];
return [dayComponents day];
}
//获取月
- (NSUInteger)getMonth
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSMonthCalendarUnit) fromDate:self];
return [dayComponents month];
}
//获取年
- (NSUInteger)getYear
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSYearCalendarUnit) fromDate:self];
return [dayComponents year];
}
//获取小时
- (int )getHour {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:self];
NSInteger hour = [components hour];
return (int)hour;
}
//获取分钟
- (int)getMinute {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:self];
NSInteger minute = [components minute];
return (int)minute;
}
- (int )getHour:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:date];
NSInteger hour = [components hour];
return (int)hour;
}
- (int)getMinute:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags =NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:date];
NSInteger minute = [components minute];
return (int)minute;
}
//在当前日期前几天
- (NSUInteger)daysAgo {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit)
  fromDate:self
toDate:[NSDate date]
options:0];
return [components day];
}
//午夜时间距今几天
- (NSUInteger)daysAgoAgainstMidnight {
// get a midnight version of ourself:
NSDateFormatter *mdf = [[NSDateFormatter alloc] init];
[mdf setDateFormat:@"yyyy-MM-dd"];
NSDate *midnight = [mdf dateFromString:[mdf stringFromDate:self]];
[mdf release];

return (int)[midnight timeIntervalSinceNow] / (60*60*24) *-1;
}

- (NSString *)stringDaysAgo {
return [self stringDaysAgoAgainstMidnight:YES];
}

- (NSString *)stringDaysAgoAgainstMidnight:(BOOL)flag {
NSUInteger daysAgo = (flag) ? [self daysAgoAgainstMidnight] : [self daysAgo];
NSString *text = nil;
switch (daysAgo) {
case 0:
text = @"Today";
break;
case 1:
text = @"Yesterday";
break;
default:
text = [NSString stringWithFormat:@"%d days ago", daysAgo];
}
return text;
}
/返回一周的第几天(周末为第一天)
- (NSUInteger)weekday {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:(NSWeekdayCalendarUnit) fromDate:self];
return [weekdayComponents weekday];
}
//转为NSString类型的
+ (NSDate *)dateFromString:(NSString *)string {
return [NSDate dateFromString:string withFormat:[NSDate dbFormatString]];
}

+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format {
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:format];
NSDate *date = [inputFormatter dateFromString:string];
[inputFormatter release];
return date;
}

+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format {
return [date stringWithFormat:format];
}

+ (NSString *)stringFromDate:(NSDate *)date {
return [date string];
}

+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed {
/*
* if the date is in today, display 12-hour time with meridian,
* if it is within the last 7 days, display weekday name (Friday)
* if within the calendar year, display as Jan 23
* else display as Nov 11, 2008
*/

NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *offsetComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:today];

NSDate *midnight = [calendar dateFromComponents:offsetComponents];

NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
NSString *displayString = nil;

// comparing against midnight
if ([date compare:midnight] == NSOrderedDescending) {
if (prefixed) {
[displayFormatter setDateFormat:@"'at' h:mm a"]; // at 11:30 am
} else {
[displayFormatter setDateFormat:@"h:mm a"]; // 11:30 am
}
} else {
// check if date is within last 7 days
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay:-7];
NSDate *lastweek = [calendar dateByAddingComponents:componentsToSubtract toDate:today options:0];
[componentsToSubtract release];
if ([date compare:lastweek] == NSOrderedDescending) {
[displayFormatter setDateFormat:@"EEEE"]; // Tuesday
} else {
// check if same calendar year
NSInteger thisYear = [offsetComponents year];

NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
  fromDate:date];
NSInteger thatYear = [dateComponents year];
if (thatYear >= thisYear) {
[displayFormatter setDateFormat:@"MMM d"];
} else {
[displayFormatter setDateFormat:@"MMM d, yyyy"];
}
}
if (prefixed) {
NSString *dateFormat = [displayFormatter dateFormat];
NSString *prefix = @"'on' ";
[displayFormatter setDateFormat:[prefix stringByAppendingString:dateFormat]];
}
}

// use display formatter to return formatted date string
displayString = [displayFormatter stringFromDate:date];
[displayFormatter release];
return displayString;
}

+ (NSString *)stringForDisplayFromDate:(NSDate *)date {
return [self stringForDisplayFromDate:date prefixed:NO];
}

- (NSString *)stringWithFormat:(NSString *)format {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:format];
NSString *timestamp_str = [outputFormatter stringFromDate:self];
[outputFormatter release];
return timestamp_str;
}

- (NSString *)string {
return [self stringWithFormat:[NSDate dbFormatString]];
}

- (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateStyle:dateStyle];
[outputFormatter setTimeStyle:timeStyle];
NSString *outputString = [outputFormatter stringFromDate:self];
[outputFormatter release];
return outputString;
}
//返回周日的的开始时间
- (NSDate *)beginningOfWeek {
// largely borrowed from "Date and Time Programming Guide for Cocoa"
// we'll use the default calendar and hope for the best

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *beginningOfWeek = nil;
BOOL ok = [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek
  interval:NULL forDate:self];
if (ok) {
return beginningOfWeek;
}

// couldn't calc via range, so try to grab Sunday, assuming gregorian style
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];

/*
Create a date components to represent the number of days to subtract from the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question.  (If today's Sunday, subtract 0 days.)
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];
beginningOfWeek = nil;
beginningOfWeek = [calendar dateByAddingComponents:componentsToSubtract toDate:self options:0];
[componentsToSubtract release];

//normalize to midnight, extract the year, month, and day components and create a new date from those components.
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
  fromDate:beginningOfWeek];
return [calendar dateFromComponents:components];
}
//返回当前天的年月日.
- (NSDate *)beginningOfDay {
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
  fromDate:self];
return [calendar dateFromComponents:components];
}
//返回该月的第一天
- (NSDate *)beginningOfMonth
{
return [self dateAfterDay:-[self getDay] + 1];
}
//该月的最后一天
- (NSDate *)endOfMonth
{
return [[[self beginningOfMonth] dateafterMonth:1] dateAfterDay:-1];
}
//返回当前周的周末
- (NSDate *)endOfWeek {
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
// to get the end of week for a particular date, add (7 - weekday) days
[componentsToAdd setDay:(7 - [weekdayComponents weekday])];
NSDate *endOfWeek = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
[componentsToAdd release];

return endOfWeek;
}

+ (NSString *)dateFormatString {
return @"yyyy-MM-dd";
}

+ (NSString *)timeFormatString {
return @"HH:mm:ss";
}

+ (NSString *)timestampFormatString {
return @"yyyy-MM-dd HH:mm:ss";
}

// preserving for compatibility
+ (NSString *)dbFormatString {
return [NSDate timestampFormatString];
}

@end
分享到:
评论

相关推荐

    NSDate分类,获得对应中国农历

    本篇将详细介绍如何通过扩展NSDate分类来实现这个功能。 首先,我们需要了解iOS中处理日期的基本类——NSDate、NSCalendar、NSDateComponents等。NSDate是苹果提供的一个抽象类,代表了绝对时间,而NSCalendar则...

    NSDate-DaboExtension:NSDate分类

    `NSDate-DaboExtension`分类可能包含多种实用方法,例如: - **日期格式化**:可能提供了更便捷的方式来将`NSDate`对象转换为字符串,或者将字符串解析为`NSDate`,这通常比使用`NSDateFormatter`更加简单。 - **...

    NSDate扩展

    首先,我们可以为`NSDate`添加一个分类(Category),在Objective-C中,通过以下方式创建: ```objc // NSDate+Extension.h #import @interface NSDate (Extension) // 添加你的扩展方法 @end // NSDate+...

    iOS类的分类方法

    以下是对"iOS类的分类方法"的详细解释。 1. **类别定义** 类别定义通常以`@interface`开始,接着是目标类的名字,后面加上一个冒号和分类的名字。例如,如果我们想给NSString添加一个新的方法,可以这样写: ```...

    ios-平时项目常用分类.zip

    为了解决这个问题,可以使用前缀或者协议来确保分类方法的独特性。 DDCategoryDemo可能包含了以下常见的类别实践: 1. **NSArray+SafeAccess**:安全访问数组元素,防止因索引越界引发的运行时错误。通过添加如`- ...

    iOS分类以及工具类汇总

    这主要体现在两个方面:一是为已有类添加方法,二是对已有类进行分类组织。例如,可以为NSString类添加一个计算字符串长度的方法,或者为UIImage类添加一个处理图片的便捷方法。分类通常用于对系统类进行功能扩展,...

    iOS常用的Category分类

    NSObject是所有Objective-C对象的基类,对其进行分类可以添加通用的方法,比如`descriptionWithLocale:`用于自定义对象的描述,或者`isEqualToString:`来比较对象与字符串的等价性。 2. **NSArray/NSMutableArray ...

    HYCategory:iOS开发中常用到的分类

    HYCategory###iOS开发中常用到的分类UIView+...NSDate+Escort:一个方便使用NSDate的分类,添加了许多操作日期的方法,例如:dateAtEndOfDay返回某天的最后一个时刻的NSDate对象。NYXImagesKit:增加UIImage的许多分

    Swift版本的日历(基础版本)

    另外,"NSDate分类"这部分可能指的是开发者创建了一个名为`NSDate+Extensions`的类别(Category,在Swift中称为Extension),为`NSDate`对象添加了一些便利的方法。虽然Swift推荐使用`Date`类,但为了兼容Objective-...

    iOS常用category

    - **增加分类**:为系统类添加实用方法,比如NSDate+Extension可以添加日期处理的便捷方法。 - **分类组织代码**:将相似功能的方法归类到一个Category中,使代码结构更清晰。 - **私有方法**:在Category中定义...

    ios-类别.zip

    1. 扩展系统类:Category可以为系统类如UIImage、NSDate等添加自定义方法,解决一些特定需求。 2. 分离代码:将相似功能的方法集中到一个Category中,使代码结构更清晰,提高可读性。 3. 组合模式:Category可以看作...

    ios-iOS类目常用类目.zip

    这对于扩展系统提供的基础类或者第三方库的功能非常有用,比如给NSArray添加排序方法,给NSDate添加格式化日期的便捷方法等。 二、类目的结构 一个类目通常由两部分组成:头文件(.h)和实现文件(.m)。头文件中...

    OC Extension Time(时间).zip

    2. **时间戳转换**:可能提供了从Unix时间戳(以秒或毫秒为单位)到NSDate对象,以及从NSDate对象到时间戳的转换方法。 3. **日期格式化**:提供了格式化日期和时间的函数,例如将日期转换成"年-月-日 时:分:秒"的...

    iOS常用的类别工具类

    - **分类代码组织**:将相关的功能方法归类,使代码结构更清晰。 - **私有方法**:虽然主要用作公开接口,但也可以用于定义私有方法,避免在.m文件中过多的方法污染。 3. **类别命名规范** - 类别名通常以原类名...

    IOS应用源码之Categories.rar

    NSDate可能会有一些日期处理的便捷方法;UIColor可能会有一些预定义的颜色分类等等。 除此之外,Category还可以用于隐藏实现细节,比如私有方法。开发者可以创建一个未公开的Category,将一些不希望对外公开的方法...

    button防连续点击(runtime)

    3. 重写`sendAction:to:forEvent:`方法:这是UIButton内部用于发送动作的方法,我们将在分类中重写这个方法,加入防连续点击的逻辑。 ```objc - (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)...

    一些常用的工具类

    - 类别的分类:有时为了更好地组织代码,可以将Category分为不同的组,如UI相关的、网络相关的等。 5. **Category在实际项目中的应用** 在实际开发中,Category常用于以下场景: - 扩展系统类的功能,如NSDate的...

    平时项目常用分类

    5. **NSDate Category**: 可能包含了日期时间的处理函数,便于日期的格式化、比较、计算等操作。 6. **NSDictionary/NSMutableDictionary Category**: 可能提供了一些键值对操作的便利方法,如安全取值、反序列化等...

    Objective-C2.0程序设计 答案

    6. **分类(Class Clusters)**:这是一种设计模式,Apple在很多系统类中使用,如NSNumber和NSDate。分类隐藏了实际实现的细节,提供了一种统一的接口。 7. **属性(Properties)**:Objective-C的属性提供了自动...

Global site tag (gtag.js) - Google Analytics