【IOS类扩展之日期操作】NSDate+Helpers

import “Date.h”

@implementation NSDate(Helpers)

//获取年月日如:19871127.

- (NSString *)getFormatYearMonthDay

{

NSString *string = [NSString stringWithFormat:@”%d%02d%02d”,[self getYear],[self getMonth],[self getDay]];

return string;

}

//该日期是该年的第几周

- (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

时间: 2024-09-29 19:12:12

【IOS类扩展之日期操作】NSDate+Helpers的相关文章

关于iOS 类扩展Extension的进一步深层理解

很多人可能会问  iOS的分类和扩展的区别,网上很多的讲解,但是一般都是分类讲的多,而这也是我们平常比较常用的知识:但是,对于扩展,总觉得理解的朦朦胧胧,不够透彻. 这里就讲一下我自己的理解,但是这个理解也是集合了前辈的经验来的,只不过我用大白文再延伸一点. 对于类扩展,先看这段话: 我们定义类时,在.h里写的变量如果不是public一般不能被外部直接调用,如果我有的方法不想被外部调用只给内部使用呢?至此,延展出现. 其实,延展就是类似于"定义私有方法"的一种子类. 对于如何创建: 通

iOS - 类扩展与分类的区别

类扩展 (Class Extension也有人称为匿名分类) 作用: 能为某个类附加额外的属性,成员变量,方法声明 一般的类扩展写到.m文件中 一般的私有属性写到类扩展 使用格式: @interface Mitchell() //属性 //方法 @end 与分类的区别 分类的小括号中必须有名字 @interface 类名(分类名字) /*方法声明*/ @end @implementation类名(分类名字) /*方法实现*/ @end 分类只能扩充方法,不能扩展属性和成员变量(如果包含成员变量会

iOS 类文件重命名操作步骤

为class修改名字: 1. 在头文件中双击选中类名:@interface之后即为类名 (不选中,则重命名选项将是disable的状态): 2. 工具栏中选择 Edit-Refactor - Rename: 3. 修改名字后,预览所有会发生的改动,选择需要的改动,最后Save保存. 参考链接:http://stackoverflow.com/questions/992381/rename-a-class-in-xcode-refactor-is-grayed-out-disabled-why

NSDate 总结日期操作

IOS Object-c NSDate总结日期操作 //NSDate //1, 创建NSDate对象 NSDate *nowDate = [NSDate date]; NSLog(@"%@",nowDate); //2, 创建明天现在的时间 NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:24*3600]; NSLog(@"%@",tomorrow); //3, 创建昨天现在的时间 NSDate *ye

【IOS学习笔记】Swift iOS 日期操作:NSDate、NSDateFormatter(转载)

转载自:http://blog.csdn.net/jinnchang/article/details/44592801 1.日期(NSDate) [objc] view plaincopy // 1.初始化 // 初始化一个当前时刻对象 var now = NSDate() // 初始化一个明天当前时刻对象 var tomorrow = NSDate(timeIntervalSinceNow: 24*60*60) // 初始化一个昨天当前时刻对象 var yestoday = NSDate(ti

JAVA笔记10__Math类、Random类、Arrays类/日期操作类/对象比较器/

/** * Math类.Random类.Arrays类:具体查JAVA手册...... */ public class Main { public static void main(String[] args) { String[] s1 = {"a","b","c","d","e"}; String[] s2 = {"a","b","c",&qu

PHP日期操作类代码-农历-阳历转换、闰年、计算天数等

这是一个实用的PHP日期时间操作类,里面包括了公历-农历转换.转换成中文日期格式.计算农历相隔天数.根据阴历年获取生肖.获取阴历月份的天数.获取农历每年的天数.获取闰月.计算阴历日期与正月初一相隔的天数.计算2个公历(阳历)日期之间的天数.根据距离正月初一的天数计算阴历日期.获取天干地支纪年等,PHP日期操作类:Lunar.class.php代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

IOS中 类扩展 xib

IOS中 类扩展 xib 一.类扩展(class extension,匿名分类) 1.格式 @interface 类名 () { // 成员变量... } // 方法声明... @end 2.作用 1> 写在.m文件中 2> 一般用来扩充私有成员变量.@property属性.方法等 二.随机数生成 1.arc4random() 会生成任意正整数和0 2.arc4random_uniform(100) 会生成0~99的整数(包括0和99) 三.UIView常见方法 1.addSubview:(U

Java入门——日期操作类

Java入门——日期操作类 Date类 是一个较为简单的操作类,使用java.util.Data类的构造方法并进行输出就可以得到一个完整的日期.构造方法为: public Data(); java.util包需要导入 package Sep26; import java.util.Date; public class DataDemo01 { public static void main(String[] args) { Date date=new Date(); System.out.pri