//
//  NSDate+Helper.m
//  BeepBeep
//
//  Created by Michael Nguyen on 4/6/16.
//  Copyright © 2016 lenpham. All rights reserved.
//

#import "NSDate+Helper.h"
//Date time type
#define MANAPP_DATETIME_DEFAULT_TYPE		NSDateFormatterMediumStyle
#define MANAPP_DATETIME_TIME_DEFAULT_TYPE	NSDateFormatterMediumStyle
#define MANAPP_TIME_DEFAULT_TYPE			NSDateFormatterShortStyle
@implementation NSDate (Helper)

/*
 * This guy can be a little unreliable and produce unexpected results,
 * you're better off using daysAgoAgainstMidnight
 */
- (NSUInteger)daysAgo
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    NSDateComponents *components = [calendar components:(NSCalendarUnitDay)
                                               fromDate:self
                                                 toDate:[NSDate date]
                                                options:0];
    
    return [components day];
}

- (NSUInteger)daysAgoAgainstMidnight
{
    // get a midnight version of ourself:
    NSDateFormatter *mdf = [self dateFormatter];
    
    [mdf setDateFormat:@"yyyy-MM-dd"];
    NSDate *midnight = [mdf dateFromString:[mdf stringFromDate:self]];
    
    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:@"%ld days ago", (unsigned long)daysAgo];
    }
    return text;
}

- (NSUInteger)weekday
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *weekdayComponents = [calendar components:(NSCalendarUnitWeekday) fromDate:self];
    
    return [weekdayComponents weekday];
}

+ (NSDate *)fromString:(NSString *)string
{
    return [NSDate dateFromString:string withStyle:MANAPP_DATETIME_DEFAULT_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 setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    [inputFormatter setTimeZone:[NSDate defaultTimeZone]];
    [inputFormatter setDateFormat:format];
    NSDate *date = [inputFormatter dateFromString:string];
    return date;
}

+ (NSDate *)dateFromString:(NSString *)string withStyle:(NSDateFormatterStyle)style
{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc]init];
    
    [inputFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    
    [inputFormatter setDateStyle:style];
    NSDate *date = [inputFormatter dateFromString:string];
    return date;
}

+ (NSString *)stringFromDate:(NSDate *)date withStyle:(NSDateFormatterStyle)style
{
    return [date stringWithStyle:style];
}

+ (NSString *)stringFromDateTime:(NSDate *)date withStyle:(NSDateFormatterStyle)style
{
    return [date stringWithDateTimeStyle:style];
}

+ (NSString *)stringFromTime:(NSDate *)date withStyle:(NSDateFormatterStyle)style
{
    return [date stringWithTimeOnlyStyle:style];
}

+ (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 alwaysDisplayTime:(BOOL)displayTime
{
    /*
     * 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
     */
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
    
    [displayFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    
    NSDate *today = [NSDate date];
    NSDateComponents *offsetComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                                     fromDate:today];
    
    NSDate *midnight = [calendar dateFromComponents:offsetComponents];
    NSString *displayString = nil;
    
    // comparing against midnight
    NSComparisonResult midnight_result = [date compare:midnight];
    
    if (midnight_result == 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];
        NSComparisonResult lastweek_result = [date compare:lastweek];
        
        if (lastweek_result == NSOrderedDescending) {
            if (displayTime) {
                [displayFormatter setDateFormat:@"EEEE h:mm a"];
            }
            else {
                [displayFormatter setDateFormat:@"EEEE"]; // Tuesday
            }
        }
        else {
            // check if same calendar year
            NSInteger thisYear = [offsetComponents year];
            
            NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                                           fromDate:date];
            NSInteger thatYear = [dateComponents year];
            
            if (thatYear >= thisYear) {
                if (displayTime) {
                    [displayFormatter setDateFormat:@"MMM d h:mm a"];
                }
                else {
                    [displayFormatter setDateFormat:@"MMM d"];
                }
            }
            else {
                if (displayTime) {
                    [displayFormatter setDateFormat:@"MMM d, yyyy h:mm a"];
                }
                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];
    
    return displayString;
}

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

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

- (NSString *)stringWithFormat:(NSString *)format
{
    NSDateFormatter *outputFormatter = [self dateFormatter];
    
    [outputFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    [outputFormatter setTimeZone:[NSDate defaultTimeZone]];
    [outputFormatter setDateFormat:format];
    NSString *timestamp_str = [outputFormatter stringFromDate:self];
    return timestamp_str;
}

- (NSString *)stringWithFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone
{
    NSDateFormatter *outputFormatter = [self dateFormatter];
    
    [outputFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    [outputFormatter setTimeZone:timeZone ? timeZone :[NSTimeZone localTimeZone]];
    [outputFormatter setDateFormat:format];
    NSString *timestamp_str = [outputFormatter stringFromDate:self];
    return timestamp_str;
}

- (NSString *)stringWithStyle:(NSDateFormatterStyle)style
{
    NSDateFormatter *outputFormatter = [self dateFormatter];
    
    [outputFormatter setDateStyle:style];
    NSString *timestamp_str = [outputFormatter stringFromDate:self];
    return timestamp_str;
}

- (NSString *)stringWithDateTimeStyle:(NSDateFormatterStyle)style
{
    NSDateFormatter *outputFormatter = [self dateFormatter];
    
    [outputFormatter setDateStyle:style];
    [outputFormatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *timestamp_str = [outputFormatter stringFromDate:self];
    return timestamp_str;
}

- (NSString *)stringWithTimeOnlyStyle:(NSDateFormatterStyle)style
{
    NSDateFormatter *outputFormatter = [self dateFormatter];
    
    [outputFormatter setTimeStyle:style];
    NSString *timestamp_str = [outputFormatter stringFromDate:self];
    return timestamp_str;
}

- (NSString *)toString
{
    return [NSDate stringFromDate:self withStyle:MANAPP_DATETIME_DEFAULT_TYPE];
}

- (NSString *)toTimeString
{
    return [NSDate stringFromDateTime:self withStyle:MANAPP_DATETIME_DEFAULT_TYPE];
}

- (NSString *)toTimeOnlyString
{
    return [NSDate stringFromTime:self withStyle:MANAPP_TIME_DEFAULT_TYPE];
}

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

- (NSString *)stringWithDateStyle:(NSDateFormatterStyle)dateStyle timeStyle:(NSDateFormatterStyle)timeStyle
{
    NSDateFormatter *outputFormatter = [self dateFormatter];
    
    [outputFormatter setDateStyle:dateStyle];
    [outputFormatter setTimeStyle:timeStyle];
    NSString *outputString = [outputFormatter stringFromDate:self];
    return outputString;
}

//negative value if the date is before the current date
- (NSInteger)numberOfDayUntilDate:(NSDate *)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    
    NSDateComponents *components = [calendar components:NSCalendarUnitDay
                                               fromDate:self
                                                 toDate:date
                                                options:0];
    
    return components.day;
}

- (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:NSCalendarUnitWeekday 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];
    
    //normalize to midnight, extract the year, month, and day components and create a new date from those components.
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                               fromDate:beginningOfWeek];
    return [calendar dateFromComponents:components];
}

- (NSDate *)beginningOfDay
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Get the weekday component of the current date
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                               fromDate:self];
    
    return [calendar dateFromComponents:components];
}

- (NSDate *)OneAmOfDay
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Get the weekday component of the current date
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
                                               fromDate:self];
    
    [components setHour:1];
    return [calendar dateFromComponents:components];
}

- (NSDate *)toLocalTime
{
    NSTimeZone *tz = [NSTimeZone localTimeZone];
    NSInteger seconds = [tz secondsFromGMTForDate:self];
    
    return [NSDate dateWithTimeInterval:seconds sinceDate:self];
}

- (NSDate *)toGlobalTime
{
    NSTimeZone *tz = [NSTimeZone localTimeZone];
    NSInteger seconds = -[tz secondsFromGMTForDate:self];
    
    return [NSDate dateWithTimeInterval:seconds sinceDate:self];
}

- (NSDate *)beginningAtMidnightOfDay
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Get the weekday component of the current date
    NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:self];
    
    components.hour = 0;
    components.minute = 0;
    components.second = 0;
    return [calendar dateFromComponents:components];
}

- (NSDate *)endOfWeek
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // Get the weekday component of the current date
    NSDateComponents *weekdayComponents = [calendar components:NSCalendarUnitWeekday 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])]; //7-> 8
    NSDate *endOfWeek = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
    
    return endOfWeek;
}

// Cuongnt changed: can change follow to expected Fomat

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

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

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

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

+ (NSDate *)parseDate:(NSString *)inStrDate format:(NSString *)inFormat
{
    NSDateFormatter *dtFormatter = [[NSDateFormatter alloc] init];
    
    [dtFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    [dtFormatter setDateFormat:inFormat];
    NSDate *dateOutput = [dtFormatter dateFromString:inStrDate];
    return dateOutput;
}

- (NSDate *)dateOnly
{
    unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:flags fromDate:self];
    NSDate *dateOnly = [calendar dateFromComponents:components];
    
    return dateOnly;
}

- (NSDate *)dateByAddSecond:(NSInteger)seconds
{
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    NSDateComponents *dayComponent = [[NSDateComponents alloc]init];
    
    dayComponent.second = seconds;
    return [theCalendar dateByAddingComponents:dayComponent toDate:self options:0];
}

- (NSDate *)dateByAddMinute:(NSInteger)minutes
{
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    NSDateComponents *dayComponent = [[NSDateComponents alloc]init];
    
    dayComponent.minute = minutes;
    return [theCalendar dateByAddingComponents:dayComponent toDate:self options:0];
}

- (NSDate *)dateByAddDays:(NSInteger)days
{
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    NSDateComponents *dayComponent = [[NSDateComponents alloc]init];
    
    dayComponent.day = days;
    return [theCalendar dateByAddingComponents:dayComponent toDate:self options:0];
}

- (NSDate *)dateByAddMonth:(NSInteger)months
{
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    NSDateComponents *monthComponent = [[NSDateComponents alloc]init];
    
    monthComponent.month = months;
    return [theCalendar dateByAddingComponents:monthComponent toDate:self options:0];
}

- (NSDate *)dateByAddingYears:(NSUInteger)years
{
    NSDateComponents *c = [[NSDateComponents alloc] init];
    
    c.year = years;
    return [[NSCalendar currentCalendar] dateByAddingComponents:c toDate:self options:0];
}

+ (NSDate *)lastDateOfMonth:(NSDate *)month
{
    NSDate *nextMonth = [month dateByAddMonth:1];
    
    return [nextMonth dateByAddDays:-1];
}

+ (NSDate *)firstDateOfMonth:(NSDate *)month
{
    NSDate *previousMonth = [month dateByAddMonth:-1];
    
    return [previousMonth dateByAddDays:1];
}

+ (NSDate *)lastDateOfWeek:(NSDate *)week
{
    return [week dateByAddDays:7];
}

+ (NSDateComponents *)hourComponentsBetweenDate:(NSDate *)firstDate andDate:(NSDate *)endDate
{
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *components = [gregorianCalendar components:unitFlags
                                                        fromDate:firstDate
                                                          toDate:endDate
                                                         options:0];
    
    return components;
}

+ (NSInteger)dayBetweenDay:(NSDate *)firstDay andDay:(NSDate *)lastDay
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDateComponents *components = [calendar components:NSCalendarUnitDay
                                               fromDate:firstDay
                                                 toDate:lastDay
                                                options:0];
    
    return components.day;
}

- (NSInteger)getMonth
{
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitYear;
    NSDateComponents *components = [gregorianCalendar components:unitFlags fromDate:self];
    
    return components.month;
}

- (NSInteger)getDay
{
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitYear;
    NSDateComponents *components = [gregorianCalendar components:unitFlags fromDate:self];
    
    return components.day;
}

- (NSInteger)getYear
{
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSUInteger unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitYear;
    NSDateComponents *components = [gregorianCalendar components:unitFlags fromDate:self];
    
    return components.year;
}

+ (NSInteger)dayUntilBirthDate:(NSDate *)birthDate
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *thisYearComponents = [calendar components:NSCalendarUnitYear fromDate:[NSDate date]];
    NSDateComponents *birthDayComponents = [calendar components:NSCalendarUnitMonth | NSCalendarUnitDay fromDate:birthDate];
    
    [birthDayComponents setYear:[thisYearComponents year]];
    
    NSDate *birthDayThisYear = [calendar dateFromComponents:birthDayComponents];
    NSDateComponents *difference = [calendar components:NSCalendarUnitDay fromDate:[NSDate date] toDate:birthDayThisYear options:0];
    
    if ([difference day] > 0) {
        // this years birthday is already over. calculate distance to next years birthday
        [birthDayComponents setYear:[thisYearComponents year] + 1];
        birthDayThisYear = [calendar dateFromComponents:birthDayComponents];
        difference = [calendar components:NSCalendarUnitDay fromDate:[NSDate date] toDate:birthDayThisYear options:0];
    }
    
    return [difference day];
}

#pragma mark - compare datetime

- (BOOL)isLaterThanOrEqualTo:(NSDate *)date
{
    return !([self compare:date] == NSOrderedAscending);
}

- (BOOL)isEarlierThanOrEqualTo:(NSDate *)date
{
    return !([self compare:date] == NSOrderedDescending);
}

- (BOOL)isLaterThan:(NSDate *)date
{
    return ([self compare:date] == NSOrderedDescending);
}

- (BOOL)isEarlierThan:(NSDate *)date
{
    return ([self compare:date] == NSOrderedAscending);
}

- (BOOL)isAfterDate:(NSDate *)date
{
    if ([self compare:date] == NSOrderedDescending) {
        return YES;
    }
    else {
        return NO;
    }
}

- (BOOL)isBetweenDate:(NSDate *)start end:(NSDate *)end
{
    if ([self isAfterDate:start] && [end isAfterDate:self]) {
        return YES;
    }
    return NO;
}

+ (NSString *)toStringWithOutSimiColon:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    
    [dateFormatter setDateFormat:@"MMMM dd yyyy hh:mm a"];
    NSString *formattedDateString = [dateFormatter stringFromDate:date];
    return formattedDateString;
}

+ (NSString *)toStringWithOutSimiColonWithOutTime:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    
    [dateFormatter setDateFormat:@"MMMM dd yyyy"];
    NSString *formattedDateString = [dateFormatter stringFromDate:date];
    return formattedDateString;
}

+ (BOOL)isAllDayEvent:(NSDate *)startDate withEndDate:(NSDate *)endDate
{
    BOOL isAllDayEvent = NO;
    NSDateComponents *dateComponents = [NSDate hourComponentsBetweenDate:startDate andDate:endDate];
    
    NSLog(@"hour %ld", (long)dateComponents.hour);
    NSLog(@"minute %ld", (long)dateComponents.minute);
    
    if ((dateComponents.hour == 24) || (dateComponents.hour == 23 && dateComponents.minute >= 57)) {
        isAllDayEvent = YES;
    }
    return isAllDayEvent;
}

- (BOOL)isSameDay:(NSDate *)anotherDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    NSDateComponents *components1 = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self];
    NSDateComponents *components2 = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:anotherDate];
    
    return ([components1 year] == [components2 year] && [components1 month] == [components2 month] && [components1 day] == [components2 day]);
}

- (NSInteger)daysBetweenDate:(NSDate *)d
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDate *startDate = [self dateOnly];
    NSDate *endDate = [d dateOnly];
    
    NSDateFormatter *formatter = [self dateFormatter];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    startDate = [formatter dateFromString:[startDate stringWithFormat:@"yyyy-MM-dd"]];
    endDate = [formatter dateFromString:[endDate stringWithFormat:@"yyyy-MM-dd"]];
    
    NSInteger startDay = [calendar ordinalityOfUnit:NSCalendarUnitDay
                                             inUnit:NSEraCalendarUnit forDate:startDate];
    NSInteger endDay = [calendar ordinalityOfUnit:NSCalendarUnitDay
                                           inUnit:NSEraCalendarUnit forDate:endDate];
    return labs(endDay - startDay);
}

- (NSString *)convertDateToDurationString
{
    NSString *suffix = @"";
    NSInteger quantity = 0;
    
    //Year
    ([self yearsAgo] > 0) ? (suffix = @"years ago") : (suffix = @"");
    
    if (suffix.length > 0) {
        quantity = [self yearsAgo];
        (quantity == 1) ? (suffix = @"year ago") : (suffix = @"years ago");
        return [NSString stringWithFormat:@"%zd %@", quantity, suffix];
    }
    //Month
    NSInteger _month = [self monthsBetweenDateInSameYear];
    (_month > 0) ? (suffix = @"months ago") : (suffix = @"");
    
    if (suffix.length > 0) {
        quantity = _month;
        (quantity == 1) ? (suffix = @"month ago") : (suffix = @"months ago");
        return [NSString stringWithFormat:@"%zd %@", quantity, suffix];
    }
    //Week
    NSInteger _week = [self weekBetweenDateInSameMonth];
    (_week > 0) ? (suffix = @"weeks ago") : (suffix = @"");
    
    if (suffix.length > 0) {
        quantity = _week;
        (quantity == 1) ? (suffix = @"week ago") : (suffix = @"weeks ago");
        return [NSString stringWithFormat:@"%zd %@", quantity, suffix];
    }
    
    //Day
    NSInteger _day = [self daysBetweenDateInSameWeek];
    (_day > 0) ? (suffix = @"days ago") : (suffix = @"");
    
    if (suffix.length > 0) {
        quantity = _day;
        (quantity == 1) ? (suffix = @"day ago") : (suffix = @"days ago");
        return [NSString stringWithFormat:@"%zd %@", quantity, suffix];
    }
    //Hour
    NSInteger _hour = [self hoursBetweenDateInSameDay];
    (_hour > 0) ? (suffix = @"hours ago") : (suffix = @"");
    
    if (suffix.length > 0) {
        quantity = _hour;
        (quantity == 1) ? (suffix = @"hour ago") : (suffix = @"hours ago");
        return [NSString stringWithFormat:@"%zd %@", quantity, suffix];
    }
    
    //Minute
    NSInteger _minutes = [self minuteBetweenDateInSameHour];
    (_minutes > 0) ? (suffix = @"minutes ago") : (suffix = @"");
    
    if (suffix.length > 0) {
        quantity = _minutes;
        (quantity == 1) ? (suffix = @"minute ago") : (suffix = @"minutes ago");
        return [NSString stringWithFormat:@"%zd %@", quantity, suffix];
    }
    else {
        return @"Few seconds ago";
    }
}

- (NSInteger)minuteBetweenDateInSameHour
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSWeekCalendarUnit | NSCalendarUnitDay | NSHourCalendarUnit | NSMinuteCalendarUnit
                                               fromDate:self
                                                 toDate:[NSDate date]
                                                options:0];
    
    return [components minute];
}

- (NSInteger)hoursBetweenDateInSameDay
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSWeekCalendarUnit | NSCalendarUnitDay | NSHourCalendarUnit | NSMinuteCalendarUnit
                                               fromDate:self
                                                 toDate:[NSDate date]
                                                options:0];
    
    return [components hour];
}

- (NSInteger)yearsAgo
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSWeekCalendarUnit | NSCalendarUnitDay | NSHourCalendarUnit | NSMinuteCalendarUnit
                                               fromDate:self
                                                 toDate:[NSDate date]
                                                options:0];
    
    return [components year];
}

- (NSInteger)daysBetweenDateInSameWeek
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSWeekCalendarUnit | NSCalendarUnitDay | NSHourCalendarUnit | NSMinuteCalendarUnit
                                               fromDate:self
                                                 toDate:[NSDate date]
                                                options:0];
    
    return [components day];
}

- (NSInteger)monthsBetweenDateInSameYear
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSWeekCalendarUnit | NSCalendarUnitDay | NSHourCalendarUnit | NSMinuteCalendarUnit
                                               fromDate:self
                                                 toDate:[NSDate date]
                                                options:0];
    
    return [components month];
}

- (NSInteger)weekBetweenDateInSameMonth
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSWeekCalendarUnit | NSCalendarUnitDay | NSHourCalendarUnit | NSMinuteCalendarUnit
                                               fromDate:self
                                                 toDate:[NSDate date]
                                                options:0];
    
    return [components weekOfMonth];
}

- (NSString *)getTimeStr
{
    NSDateFormatter *formatter = [self dateFormatter];
    
    [formatter setDateFormat:@"h:mm a"];
    
    //Optionally for time zone conversions
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
    
    NSString *stringFromDate = [formatter stringFromDate:self];
    return stringFromDate;
}

- (NSString *)getDateStr
{
    NSDateFormatter *formatter = [self dateFormatter];
    
    [formatter setDateFormat:@"yyyy/MM/dd"];
    
    //Optionally for time zone conversions
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
    
    NSString *stringFromDate = [formatter stringFromDate:self];
    return stringFromDate;
}

- (NSDate *)setTimeWithTimeStr:(NSString *)timeStr
{
    NSString *dateStr = [self getDateStr];
    
    NSDateFormatter *formatter = [self dateFormatter];
    
    [formatter setDateFormat:@"yyyy/MM/dd h:mm a"];
    
    NSString *dateFullStr = [NSString stringWithFormat:@"%@ %@", dateStr, timeStr];
    NSDate *newDate = [formatter dateFromString:dateFullStr];
    return newDate;
}

#pragma mark - NSDateFormatter
- (NSDateFormatter *)dateFormatter
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"ja_JP"]];
    
    return formatter;
}

+ (NSTimeZone *)defaultTimeZone
{
  return [NSTimeZone localTimeZone];
}

@end
