"Date operation for iOS class extensions" Nsdate+helpers

Source: Internet
Author: User
Tags dateformat

Import "Date.h"

@implementation NSDate (Helpers)

Get Date: 19871127.
-(NSString *) getformatyearmonthday
{
NSString *string = [NSString stringwithformat:@ "%d%02d%02d", [Self getyear],[self getmonth],[self GetDay]];
return string;
}

The date is the week ordinal of the year
-(int) getweekofyear
{
int i;
int year = [self getYear];
NSDate *date = [self endofweek];
for (i = 1;[ [Date dateafterday:-7 * i] getYear] = = year;i++)
{
}
return i;
}
Date of day days (if days is negative, the date before |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;

}
Date months after 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;

}
Get Day
-(Nsuinteger) getday{
Nscalendar *calendar = [Nscalendar Currentcalendar];
nsdatecomponents *daycomponents = [Calendar components: (Nsdaycalendarunit) fromdate:self];
return [daycomponents Day];
}
Get month
-(Nsuinteger) GetMonth
{
Nscalendar *calendar = [Nscalendar Currentcalendar];
nsdatecomponents *daycomponents = [Calendar components: (Nsmonthcalendarunit) fromdate:self];
return [daycomponents month];
}
Get year
-(Nsuinteger) getYear
{
Nscalendar *calendar = [Nscalendar Currentcalendar];
nsdatecomponents *daycomponents = [Calendar components: (Nsyearcalendarunit) fromdate:self];
return [daycomponents year];
}
Get hours
-(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;
}
Get minutes
-(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;
}
Days before the current date
-(Nsuinteger) Daysago {
Nscalendar *calendar = [Nscalendar Currentcalendar];
nsdatecomponents *components = [Calendar components: (Nsdaycalendarunit)
Fromdate:self
Todate:[nsdate Date]
OPTIONS:0];
return [Components day];
}
Midnight time is a few days from now
-(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;
      }

Returns the day ordinal of a week (the first day of the weekend)
-(Nsuinteger) weekday {
Nscalendar *calendar = [Nscalendar Currentcalendar];
nsdatecomponents *weekdaycomponents = [Calendar components: (Nsweekdaycalendarunit) fromdate:self];
return [weekdaycomponents weekday];
}
Convert to NSString type
+ (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 on 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) {
    [disp Layformatter setdateformat:@ "' at ' h:mm a"]; At 9:00AM
    } else {
    [displayformatter setdateformat:@ "h:mm a"];//AM
    }
    } else {
    //CHEC K 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;
    }
    Returns the start time of Sunday

  • (NSDate *) Beginningofweek {
    Largely borrowed from "Date and time Programming Guide for Cocoa"
    We ' ll use the default calendar and hope

    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 represent the number of days to subtract from the current date.
    The weekday value for Sunday in the Gregorian calendar are 1, so subtract 1 from the number of days to subtract from the DA Te 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, month, and day, and create a new date from those.
    nsdatecomponents *components = [Calendar components: (Nsyearcalendarunit | Nsmonthcalendarunit | Nsdaycalendarunit)
    Fromdate:beginningofweek];
    return [Calendar datefromcomponents:components];
    }
    Returns the date of the current day.

  • (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];
    }
    Returns the first day of the month
  • (NSDate *) beginningofmonth
    {
    return [self dateafterday:-[self getDay] + 1];
    }
    The last day of the month
  • (NSDate *) endOfMonth
    {
    return [[Self beginningofmonth] dateaftermonth:1] dateafterday:-1];
    }
    Returns the weekend of the current week
  • (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

"Date operation for iOS class extensions" Nsdate+helpers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.