I am taking two NSDates from datepicker
I want to calculate the exact year difference between the dates..if I change the second date's day one greater, it should give me the year difference 2..and if take the day lesser it should give me 0 year difference..how can I achieve that? please help me..
this is my code to calculate difference
NSCalendar *gregorian1 = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit;
NSDateComponents *components1 = [gregorian1 components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger diff = [components1 year];
Try this:
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:dateA
toDate:dateB
options:0];
NSLog(#"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
As the result you have difference in date components.
Swift 3
extension Date{
func yearsTo(_ date : Date) -> Int{
return Calendar.current.dateComponents([.year], from: self, to: date).year ?? 0
}
}
Related
I have to find next Sunday date (NSDate) from device's current date.
I have used below logic:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self];
NSUInteger weekdayToday = [components weekday];
NSInteger daysToMonday = (8 - weekdayToday) % 7;
NSDate *weekEndPrev = [self dateByAddingTimeInterval:60*60*24*daysToMonday];
Here, in EST if time is near to 11 PM, I'm getting Monday as Weekend.
Let me know feasible solution. I have tried many options. Nothings works with 2 different timezones.
Thanks in Advance.
You need just to get the number of days you need and then just add them to your current date:
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate * newDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:value toDate:date options:0];
where value - is the number of days to add
Find current week Sunday Date first then add 7 days using NSDateComponents.
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *weekdayComponents = [gregorian components:NSCalendarUnitWeekday fromDate:today];
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay:(0 - ([weekdayComponents weekday] - 1))];
NSDate *sudayCurWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:7];
NSDate *nextSunday = [gregorian dateByAddingComponents:offsetComponents toDate:sudayCurWeek options:0];
NSLog(#"%#",nextSunday);
You can do this without any math, which is best left to NSCalendar as it handles daylight savings etc. First you need a calendar with the correct time zone. For example for IST:
NSCalendar *gc = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
gc.timeZone = [NSTimeZone timeZoneWithName:#"IST"];
Then you can use nextDateAfterDate:matchingUnit:value:options: to find the start of the next Sunday after a given time. For example:
NSDate *start = ... // the time you wish to start from
NSDate *nextSunday =
[gc nextDateAfterDate:start
matching:UnitNSCalendarUnitWeekday // match based on weekday number
value:1 // Sunday = weekday 1
options:NSCalendarMatchNextTime // read the docs!
];
The returned date, nextSunday, will be the next Sunday at 00:00 in the timezone of the calendar, gc.
HTH
Finally, I got solution..
NSDateComponents *components = [[NSCalendar currentCalendar] componentsInTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"] fromDate:[NSDate date]]; // Pass date for which you want to find next Sunday
NSUInteger weekdayToday = [components weekday];
NSInteger daysToMonday = (8 - weekdayToday) % 7;
NSDate *weekEndPrev = [[NSDate date] dateByAddingTimeInterval:60*60*24*daysToMonday];
Hello I have a date string like this.11/14/2016. What I want to do is check it whether is it
Today or This week or This month. I can compare today and the month. But how can I check whether this date belongs to "This Week"
Please help me.
Thanks
Given two dates,
NSDate *now = [NSDate date];
NSDate *then = // some other date
Find out if they're in the same week with:
BOOL sameWeek = [[NSCalendar currentCalendar] isDate:then equalToDate:now
toUnitGranularity:NSCalendarUnitWeekOfYear];
That line asks if they're "equal" with a granularity of a week, meaning that they're "equal" if they're in the same week.
Try below code,
- (void)thisWeek:(NSDate *)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:date];
NSUInteger datesWeek = [otherComponents weekOfYear];
//NSLog(#"Date %#",date);
if(todaysWeek==datesWeek){
NSLog(#"Date is in this week");
}else if(todaysWeek+1==datesWeek){
NSLog(#"Date is in next week");
}
}
I want to update label that shows time left between 2 nsdates everysecond.
my code is below :
NSDate *nowDate = [NSDate date];
double diff = [campaignDate timeIntervalSince1970] - [nowDate timeIntervalSince1970];
int diff_day = diff/60/60/24 - 1;
int diff_hour = ((int)diff/60/60)%24;
int diff_min = ((int)diff/60)%60;
int diff_sec = ((int)diff/60/60)%60;
When i logged diff_sec , it always shows me 49
day,hour and min value is printed in working order
why does that diff_sec make a problem? is there any solution ?
I think you should use NSDateComponents to get the number of days/hours/minutes/seconds between two days.
Then you can get the remaing time like this:
NSDate *fromDate = [NSDate date];
NSDate *toDate = [NSDate dateWithTimeIntervalSinceNow:12345];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:fromDate toDate:toDate options:0];
NSLog(#"Event in %# days, %#:%#:%#", #(difference.day), #(difference.hour), #(difference.minute), #(difference.second));
Use NSCalendar
NSDate *dateA;
NSDate *dateB;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:dateA
toDate:dateB
options:0];
NSLog(#"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
The error is in calculating diff_sec, the divisions by 60 are incorrect because diff is already in seconds.
Incorrect code:
int diff_sec = ((int)diff/60/60)%60;
Correct code
int diff_sec = ((int)diff)%60;
I am trying to determine if the current date is in fact three days or less from the end of the month. In other words, if I am in August, then I would like to be alerted if it is the 28,29,30, or 31st. If I am in February, then I would like to be notified when it is the 25,26,27, or 28 (or even 29). In the case of a leap year, I would be alerted from 26th onwards.
My problem is that I am not sure how to perform such a check so that it works for any month. Here is my code that I have thus far:
-(BOOL)monthEndCheck {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
if (month is 3 days or less from the end of the month for any month) {
return YES;
} else {
return NO;
}
}
Because there are months with 28, 30, and 31 days, I would like a dynamic solution, rather than creating a whole series of if/else statements for each and every condition. Is there a way to do this?
This is how you get the last day of the month:
NSDate *curDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; // Get necessary date components
// set last of month
[comps setMonth:[comps month]+1];
[comps setDay:0];
NSDate *tDateMonth = [calendar dateFromComponents:comps];
NSLog(#"%#", tDateMonth);
Source: Getting the last day of a month
EDIT (another source): How to retrive Last date of month give month as parameter in iphone
Now you can simply count from the current date.
If < 3 do whatever you wanted to do.
Maybe something like this:
NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
double timeInSecondsFor3Days = 280000; //Better use NSDateComponents here!
NSInteger hoursBetweenDates = distanceBetweenDates / timeInSecondsFor3Days;
However I did not test that^^
EDIT: Thanks to Aaron. Do NSDateComponents to calculate the time for three days instead!
First you have to compute the start of the current day (i.e. today at 00.00).
Otherwise, the current day will not count as a full day when computing the
difference between today and the start of the next month.
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startOfToday;
[cal rangeOfUnit:NSCalendarUnitDay startDate:&startOfToday interval:NULL forDate:now];
Computing the start of the next month can be done with rangeOfUnit:...
(using a "statement expression" to be fancy :)
NSDate *startOfNextMonth = ({
NSDate *startOfThisMonth;
NSTimeInterval lengthOfThisMonth;
[cal rangeOfUnit:NSCalendarUnitMonth startDate:&startOfThisMonth interval:&lengthOfThisMonth forDate:now];
[startOfThisMonth dateByAddingTimeInterval:lengthOfThisMonth];
});
And finally the difference in days:
NSDateComponents *comp = [cal components:NSCalendarUnitDay fromDate:startOfToday toDate:startOfNextMonth options:0];
if (comp.day < 4) {
// ...
}
I saw this post: iOS and finding Tomorrow.
The code provided is:
units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comps = [[NSCalendar currentCalendar] components:units fromDate:[NSDate date]];
// Add one day
comps.day = comps.day+1; // no worries: even if it is the end of the month it will wrap to the next month, see doc
// Recompose a new date, without any time information (so this will be at midnight)
NSDate* tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];
Problem: I need to add a day to my current date so that for example, the difference between 21st Jun 2013 and 21st May 2013 is 1 month instead of 0 month.
The code I am using:
NSDate *selectedDate = [picker2 date];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [currCalendar components:unitFlags fromDate:selectedDate toDate:[NSDate date] options:0];
DLog(#"%i",conversionInfo.month);
DLog(#"%i",conversionInfo.day);
conversionInfo.day +=1;
DLog(#"%i",conversionInfo.day);
DLog(#"%i",conversionInfo.month);
int months = [conversionInfo month];
But when I tried to get the difference between 21st Jun 2013 and 21st May 2013 -> still returns me 0 month instead of 1 month.
Need some help on this.
Form a date component with number of days you want to add to your original date. From the current calendar form the date by adding the this component to your original date.
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.day = 1;
NSDate *newDate = [[NSCalendar currentCalendar]dateByAddingComponents:dateComponents
toDate: selectedDate
options:0];
Here is a method I use:
+ (NSDate *)addDays:(NSInteger)days toDate:(NSDate *)originalDate {
NSDateComponents *components= [[NSDateComponents alloc] init];
[components setDay:days];
NSCalendar *calendar = [NSCalendar currentCalendar];
return [calendar dateByAddingComponents:components toDate:originalDate options:0];
}
With it, you can add as many days as you want. It also works with negative numbers, so you can subtract days.
Simple and straight forward solution :
NSDate *currentDate = [NSDate date];
NSDate *nextDate = [currentDate dateByAddingTimeInterval:(24*3600)];
This is working fine for me.
For swift googlers:
NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: 1, toDate: date, options: nil)!
First Thing,you are assigning day instead of month to NSDateComponent.
Execute following code and find difference between inDate And newDate
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitMonth fromDate:inDate];
NSInteger monthFlag = 1;
components.month = minuteFlag;
// Retrieve date with increased days count
NSDate *newDate = [[NSCalendar currentCalendar]
dateByAddingComponents:components
toDate:monthFlag
options:0];
To add any number of any components to the date, for example: 2 days or 2 months, 1 year, do the following:
Calendar.current.date(byAdding: DateComponents(month: -1), to: date)! //this create date with previous month for date.
you can initialize DateComponents with anything:
public init(calendar: Calendar? = default, timeZone: TimeZone? = default, era: Int? = default, year: Int? = default, month: Int? = default, day: Int? = default, hour: Int? = default, minute: Int? = default, second: Int? = default, nanosecond: Int? = default, weekday: Int? = default, weekdayOrdinal: Int? = default, quarter: Int? = default, weekOfMonth: Int? = default, weekOfYear: Int? = default, yearForWeekOfYear: Int? = default)