Skip to content

Instantly share code, notes, and snippets.

@pedronsouza
Created April 25, 2014 18:51
Show Gist options
  • Save pedronsouza/11299428 to your computer and use it in GitHub Desktop.
Save pedronsouza/11299428 to your computer and use it in GitHub Desktop.
Cool date extensions :D
#import "NSDate+Extensions.h"
@implementation NSDate (Extensions)
- (NSDate *)dateByMovingToBeginningOfDay {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// [calendar setLocale:[NSLocale currentLocale]];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
NSDateComponents* parts = [calendar components:flags fromDate:self];
[parts setHour:0];
[parts setMinute:0];
[parts setSecond:0];
NSDate *data;
data = [calendar dateFromComponents:parts];
return data;
}
- (NSDate *)dateByMovingToEndOfDay {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
[parts setHour:23];
[parts setMinute:59];
[parts setSecond:59];
[[NSCalendar currentCalendar] setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
return [[NSCalendar currentCalendar] dateFromComponents:parts];
}
- (NSDate *)dateByMovingToBeginningOfMonth {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
[parts setDay:1];
[parts setHour:0];
[parts setMinute:0];
[parts setSecond:0];
[[NSCalendar currentCalendar] setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
return [[NSCalendar currentCalendar] dateFromComponents:parts];
}
- (NSDate *)dateByMovingToEndOfMonth {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:self];
NSRange monthRange = [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:self];
[parts setDay:monthRange.length];
[parts setHour:23];
[parts setMinute:59];
[parts setSecond:59];
[[NSCalendar currentCalendar] setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
return [[NSCalendar currentCalendar] dateFromComponents:parts];
}
- (NSDate *)dateByMovingToBeginningOfWeek {
NSCalendar *gregorian = [NSCalendar currentCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian 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];
/* Substract [gregorian firstWeekday] to handle first day of the week being something else than Sunday */
[componentsToSubtract setDay: - ([weekdayComponents weekday] - [gregorian firstWeekday])];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:self options:0];
/*
Optional step:
beginningOfWeek now has the same hour, minute, and second as the
original date (today).
To normalize to midnight, extract the year, month, and day components
and create a new date from those components.
*/
NSDateComponents *components = [gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit)
fromDate: beginningOfWeek];
[components setHour:0];
beginningOfWeek = [gregorian dateFromComponents: components];
return beginningOfWeek;
}
+(NSDate*)dateWithddMMyyyyFormat:(NSString *)dateInddMMyyyyFormat {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
NSTimeZone *formatterTimeZone = dateFormatter.timeZone;
//Fix the bug caused by the fucking time zone at day 21/10/2013
NSTimeZone *defaultTimeZone = [NSTimeZone timeZoneWithName:@"GMT"];
[dateFormatter setTimeZone:defaultTimeZone];
NSDate *date = [dateFormatter dateFromString:dateInddMMyyyyFormat];
NSInteger hoursOffset = [formatterTimeZone secondsFromGMT] / 3600;
if([formatterTimeZone isDaylightSavingTime]){
hoursOffset -= [formatterTimeZone daylightSavingTimeOffset]/3600;
};
//Do the parsing :)
date = [date dateByAddingHours:(-hoursOffset)];
return date;
}
-(NSString*) dateToWCFFormat{
double timeSince1970=[self timeIntervalSince1970];
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
offset=offset/3600;
double nowMillis = 1000.0 * (timeSince1970);
NSString *dotNetDate=[NSString stringWithFormat:@"/Date(%.0f%+03d00)/",nowMillis,offset] ;
return dotNetDate;
}
- (NSString *)dateByFormat:(NSString *)pattern {
NSDateFormatter *formatterData = [[NSDateFormatter alloc] init];
[formatterData setDateFormat:pattern];
return [formatterData stringFromDate:self];
}
- (NSString *)dateWithLongStyleFormat{
NSDateFormatter *formatador = [[NSDateFormatter alloc] init];
NSLocale *localeBR = [[NSLocale alloc] initWithLocaleIdentifier:@"pt-br"];
[formatador setLocale:localeBR];
[formatador setDateStyle:NSDateFormatterLongStyle];
return [formatador stringFromDate:self];
}
//Retorna uma data adicionando os dias solicitados (ou removendo se for numero negativo)
- (NSDate *)dateByAddingDays:(NSInteger)days {
NSCalendar *gregorian = [NSCalendar currentCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
/*
Create a date components to represent the number of days to add
from the current date.
*/
NSDateComponents *componentsDaysToAdd = [[NSDateComponents alloc] init];
/* set the number of days to add into the current date*/
[componentsDaysToAdd setDay: days];
NSDate *finalDate = [gregorian dateByAddingComponents:componentsDaysToAdd toDate:self options:0];
return finalDate;
}
- (NSDate *)dateByAddingHours:(NSInteger)hours {
NSCalendar *gregorian = [NSCalendar currentCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
/*
Create a date components to represent the number of days to add
from the current date.
*/
NSDateComponents *componentsDaysToAdd = [NSDateComponents new];
/* set the number of days to add into the current date*/
[componentsDaysToAdd setHour: hours];
NSDate *finalDate = [gregorian dateByAddingComponents:componentsDaysToAdd toDate:self options:0];
return finalDate;
}
- (NSDate *)dateByAddingHours:(NSInteger)hours andMinutes:(NSInteger)minutes{
NSCalendar *gregorian = [NSCalendar currentCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
/*
Create a date components to represent the number of days to add
from the current date.
*/
NSDateComponents *componentsDaysToAdd = [NSDateComponents new];
/* set the number of days to add into the current date*/
[componentsDaysToAdd setHour: hours];
[componentsDaysToAdd setMinute: minutes];
NSDate *finalDate = [gregorian dateByAddingComponents:componentsDaysToAdd toDate:self options:0];
return finalDate;
}
- (NSDate *)dateByAddingMinutes:(NSInteger)minutes {
NSCalendar *gregorian = [NSCalendar currentCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
/*
Create a date components to represent the number of days to add
from the current date.
*/
NSDateComponents *componentsDaysToAdd = [NSDateComponents new];
/* set the number of days to add into the current date*/
[componentsDaysToAdd setMinute: minutes];
NSDate *finalDate = [gregorian dateByAddingComponents:componentsDaysToAdd toDate:self options:0];
return finalDate;
}
- (BOOL)isDateToday {
return [self isSameDayInOtherDate:[NSDate date]];
}
- (BOOL)isDateThisMonth {
NSUInteger dateComponents = (NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit);
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
NSDateComponents *components = [cal components:dateComponents
fromDate:[NSDate date]];
components.day = 1;
NSDate *today = [cal dateFromComponents:components];
components = [cal components:dateComponents
fromDate:self];
components.day = 1;
NSDate *otherDate = [cal dateFromComponents:components];
return [today isEqualToDate:otherDate];
}
- (BOOL)isSameDayInOtherDate:(NSDate *)otherDate {
NSUInteger dateComponents = (NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit);
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
NSDateComponents *components = [cal components:dateComponents
fromDate:self];
NSDate *date1 = [cal dateFromComponents:components];
components = [cal components:dateComponents
fromDate:otherDate];
NSDate *date2 = [cal dateFromComponents:components];
return [date1 isEqualToDate:date2];
}
-(NSInteger)daysUntilDate:(NSDate *)otherDate{
// //Instancia um calendario gregoriano
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"America/Sao_Paulo"]];
NSDate *fromDate;
NSDate *toDate;
//Pega o range em dias das datas (self e a passada por parametro)
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate
interval:NULL forDate:self];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate
interval:NULL forDate:otherDate];
//Pega a diferença em dias dos ranges
NSDateComponents *difference = [calendar components:NSDayCalendarUnit
fromDate:fromDate toDate:toDate options:0];
return difference.day;
}
- (NSInteger)dayOfWeek
{
NSDateComponents* parts = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:self];
return parts.weekday;
}
- (NSDate *)getNextWednesday
{
NSDate * nxtWed = [NSDate dateWithTimeIntervalSince1970:[self timeIntervalSince1970]];
NSInteger dow = [nxtWed dayOfWeek];
NSDate *retorno = nil;
if(dow == kDayOfWeekWednesday)
retorno = [nxtWed dateByAddingDays:7];
else if(dow < kDayOfWeekWednesday)
retorno = [nxtWed dateByAddingDays:kDayOfWeekWednesday-dow];
else
retorno = [nxtWed dateByAddingDays:kDayOfWeekWednesday-dow+7];
return retorno;
}
- (NSInteger)day
{
NSDateComponents* parts = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:self];
return parts.day;
}
- (NSInteger)month
{
NSDateComponents* parts = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit fromDate:self];
return parts.month;
}
- (NSInteger)year
{
NSDateComponents* parts = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:self];
return parts.year;
}
- (NSInteger)hour
{
NSDateComponents* parts = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:self];
return parts.hour;
}
- (CGPoint)hourAndMinute
{
NSDateComponents* parts = [[NSCalendar currentCalendar] components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:self];
return CGPointMake(parts.hour, parts.minute);
}
-(NSInteger)yearsToDate:(NSDate *)otherDate {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:self
toDate:otherDate
options:0];
return components.year;
}
-(BOOL)isSameWeekOfDate:(NSDate *)otherDate {
if(otherDate == nil) return NO;
NSDateComponents* lastParts = [[NSCalendar currentCalendar] components:NSWeekOfYearCalendarUnit fromDate:self];
NSInteger weekLast = lastParts.weekOfYear;
NSDateComponents* newParts = [[NSCalendar currentCalendar] components:NSWeekOfYearCalendarUnit fromDate:otherDate];
NSInteger weekNew = newParts.weekOfYear;
return weekLast == weekNew;
}
-(BOOL) compareDayMonthYear:(NSDate*)date2
{
if([date2 day] != [self day])
return NO;
if([date2 month] != [self month])
return NO;
if([date2 year] != [self year])
return NO;
return YES;
}
@end
#import <Foundation/Foundation.h>
typedef enum {
kDayOfWeekSunday = 1,
kDayOfWeekMonday = 2,
kDayOfWeekTuesday = 3,
kDayOfWeekWednesday = 4,
kDayOfWeekThursday = 5,
kDayOfWeekFriday= 6,
kDayOfWeekSaturday = 7
} kDayOfTheWeek;
@interface NSDate (Extensions)
- (NSDate *)dateByMovingToBeginningOfDay;
- (NSDate *)dateByMovingToEndOfDay;
- (NSDate *)dateByMovingToBeginningOfMonth;
- (NSDate *)dateByMovingToEndOfMonth;
- (NSDate *)dateByMovingToBeginningOfWeek;
+ (NSDate *)dateWithddMMyyyyFormat:(NSString*)dateInddMMyyyyFormat;
- (NSDate *)dateByAddingDays:(NSInteger)days;
- (NSDate*) dateByAddingHours:(NSInteger)hours;
- (NSDate*) dateByAddingHours:(NSInteger)hours andMinutes:(NSInteger)minutes;
- (NSDate *)dateByAddingMinutes:(NSInteger)minutes;
- (NSString *)dateToWCFFormat;
- (NSString *)dateByFormat:(NSString *)pattern;
- (NSString *)dateWithLongStyleFormat;
- (BOOL)isDateToday;
- (BOOL)isDateThisMonth;
- (BOOL)isSameDayInOtherDate:(NSDate *)otherDate;
- (NSInteger)daysUntilDate:(NSDate *)otherDate;
- (NSInteger)dayOfWeek;
- (NSDate *)getNextWednesday;
- (NSInteger)day;
- (NSInteger)month;
- (NSInteger)year;
- (NSInteger)hour;
- (CGPoint)hourAndMinute;
- (NSInteger)yearsToDate:(NSDate*)otherDate;
- (BOOL) isSameWeekOfDate:(NSDate*)otherDate;
- (BOOL) compareDayMonthYear:(NSDate*)date2;
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment