iOS one month from current Date. - ios

I'm trying to get one month from the current date.
Below is what I have and it is returning: 4027-09-24 16:59:00 +0000. currentDate is right. What's going on?
// Get todays date to set the monthly subscription expiration date
NSDate *currentDate = [NSDate date];
NSLog(#"Current Date = %#", currentDate);
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit fromDate:currentDate];
dateComponents.month = dateComponents.month + 1;
NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(#"Date = %#", currentDatePlus1Month);

Try this instead:
// Get todays date to set the monthly subscription expiration date
NSDate *currentDate = [NSDate date];
NSLog(#"Current Date = %#", currentDate);
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.month = 1;
NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(#"Date = %#", currentDatePlus1Month);

NSDate *currentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate];
// Get necessary date components
[components month]; //gives you month
[components day]; //gives you day
[components year]; //gives you year

Related

Issue with NSDate

I am having a NSDate object in format as 2018-01-19 18:30:00 +0000. Now i want to change only the time components. After changing the time components the NSDate Object would be as 2018-01-19 10:00:00. I did tried various solution but nothing worked. If any one have any solution regarding this issue help out. Thank you in advance
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: NSCalendarUnitYear| NSCalendarUnitMonth| NSCalendarUnitDay fromDate:date];
[components setHour:hour];
[components setMinute:minute];
[components setSecond:second];
NSDate *newDate = [calendar dateFromComponents:components];
another solution i tried is
NSDate *oldDate = date;
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDate];
comps.hour = 10;
comps.minute = 00;
comps.second = 00;
NSDate *newDate = [calendar dateFromComponents:comps];
Every time i get output is next date of input date
You can change the time components when you create a new NSDate object with:
NSDate *date = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];
Answer from: https://stackoverflow.com/a/5611700/4535184
Here is your code just add dateformater to formate the date
NSDate *oldDate = [[NSDate alloc]init];
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:unitFlags fromDate:oldDate];
comps.hour = 10;
comps.minute = 00;
comps.second = 00;
NSDate *newDate = [calendar dateFromComponents:comps];
NSDateFormatter *formater = [[NSDateFormatter alloc]init];
formater.dateFormat = #"YYYY-MM-dd hh:mm:ss";
NSLog(#"New Date : %#",[formater stringFromDate:newDate]);
Try this
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss zzzz"];
NSDate *date = [formatter dateFromString:#"2018-01-19 18:30:00 +0000"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: NSCalendarUnitDay| NSCalendarUnitHour| NSCalendarUnitMinute|NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:date];
[components setHour:10];
[components setMinute:0];
[components setSecond:0];
NSDate *newDate = [calendar dateFromComponents:components];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSLog(#"%#",[formatter stringFromDate:newDate]);

dateByAddingComponents:dateRange toDate:firstDate options:0 is always returning current quarter

I am using
- (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSCalendarOptions)opts
to calculate a new date, like below:
NSDateComponents *quaterComps = [NSDateComponents new];
quaterComps.quarter = 1;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *nextDate = [gregorian dateByAddingComponents:quaterComps toDate:firstDate options:0];
When firstDate is 2013-12-31 16:00:00 +0000,
Above API keeps returning the same result, not the next quarter date
** current date and next date **
NSDate *currentDate = [NSDate date];
NSDate *futureTime = [currentDate dateByAddingTimeInterval:60*60*72];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
[calendar setTimeZone:timeZone];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit fromDate:futureTime];
if ([components hour] >= 19) { // make it the next day
[components setDay:[components day] + 1 ];
}
[components setHour:8];
[components setMinute:00];
NSDate *alertTime = [calendar dateFromComponents:components];
NSDate *date = [NSDate date];
NSDateComponents *comp = [NSDateComponents new];
comp.weekOfYear = 3;
NSDate *date1 = [[NSCalendar currentCalendar] dateByAddingComponents:comp toDate:date options:0];
NSLog(#"date: %#", date);
NSLog(#"date1: %#", date1)

Get list of days from selected month

I want to get list of days in selected month.
For example, If user select feb then it show 1 to 28 0r 29 days. How can i do that?
Thanks
You can try the following code, I have given the today's date to find the list of dates in this month. You can give some other date to find the list of that given month.
NSDate *today = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSMutableArray *datesThisMonth = [NSMutableArray array];
NSRange rangeOfDaysThisMonth = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:today];
NSDateComponents *components = [cal components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSEraCalendarUnit) fromDate:today];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
for (NSInteger i = rangeOfDaysThisMonth.location; i < NSMaxRange(rangeOfDaysThisMonth); ++i) {
[components setDay:i];
NSDate *dayInMonth = [cal dateFromComponents:components];
[datesThisMonth addObject:dayInMonth];
}
NSLog(#"datesThisMonth: %#", datesThisMonth);
You can retrieve the number of days in specified month
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comps = [[NSDateComponents alloc] init];
// Set month here
[comps setMonth:2]; // 2 = February
NSRange range = [cal rangeOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:[cal dateFromComponents:comps]];
NSLog(#"current day count in this month: %lu", (unsigned long)range.length);
I have an open source calendar event project. Maybe you can check it out if you need anything.
DPCalendar
I have simplied it to
- (NSInterger) numberOfDaysForMonth:(NSDate *)date {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate: date];
[components setDay:1];
//Get the first day of the month
NSDate *firstDay = [calendar dateFromComponents:components];
[components setDay:0];
[components setMonth:components.month + 1];
//Get the last day of the month
NSDate *lastDay = [calendar dateFromComponents:components];
components = [self.calendar components:NSDayCalendarUnit fromDate:firstDay toDate:lastDay options:0];
return components.day + 1;
}
Cheers
Generally, we only need to handle Feb depend on the year, here's my method implemented:
+ (NSUInteger)numberOfDaysForYear:(NSInteger)year
month:(NSInteger)month
{
if (2 == month) {
NSCalendar * gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents * dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:year];
[dateComponents setMonth:month];
[dateComponents setDay:1];
NSDate * firstDayDate = [gregorianCalendar dateFromComponents:dateComponents];
NSRange days = [gregorianCalendar rangeOfUnit:NSCalendarUnitDay
inUnit:NSCalendarUnitMonth
forDate:firstDayDate];
return days.length;
} else if (4 == month || 6 == month || 9 == month || 11 == month) {
return 30;
} else {
return 31;
}
}

Calculating the number of days and hours between today and a future date

** Solved. Code updated to work correctly **
I'm trying to calculate the difference in days, hours, minutes, and seconds from the current date/time and a future date/time.
What have I done wrong? First of all it doesn't look like the timezone is working properly. Second of all the number of hours, minutes, and seconds are way off.
Result:
Current date: 2013-09-12 05:42:24 +0000 (should be 10:43pm PST)
Future Date: 2013-09-29 23:00:00 +0000 (should be 4pm PST)
Days: 17
Hours: 596523.235278 (should be ~425)
Minutes: 35791394 (should be ~25516)
Seconds: 2147483647 (should be ~1530960)
// Get today's Date
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian1 = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *todaysComps = [gregorian1 components: NSUIntegerMax fromDate: todaysDate];
[todaysComps setTimeZone:[NSTimeZone timeZoneWithName:#"America/Vancouver"]];
NSDate *todayFinalDate = [gregorian1 dateFromComponents: todaysComps];
NSLog(#"Current date: %#", todayFinalDate);
// Set Future Date
NSDate *futureDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: futureDate];
[todaysComps setTimeZone:[NSTimeZone timeZoneWithName:#"America/Vancouver"]];
[components setHour: 16];
[components setMinute: 00];
[components setSecond: 00];
[components setDay: 29];
[components setMonth: 9];
[components setYear: 2013];
NSDate *newDate = [gregorian dateFromComponents: components];
NSLog(#"Future Date: %#", newDate);
// Check time between the two
NSDateComponents *difference = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:todaysDate toDate:newDate options:0];
int dayDiff = [difference day];
difference = [[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:todaysDate toDate:newDate options:0];
int hourDiff = [difference hour];
difference = [[NSCalendar currentCalendar] components:NSMinuteCalendarUnit fromDate:todaysDate toDate:newDate options:0];
int minDiff = [difference minute];
difference = [[NSCalendar currentCalendar] components:NSSecondCalendarUnit fromDate:todaysDate toDate:newDate options:0];
int secDiff = [difference second];
self.daysLabel.text=[NSString stringWithFormat:#"%d",dayDiff];
self.hoursLabel.text=[NSString stringWithFormat:#"%d",hourDiff];
self.minutesLabel.text=[NSString stringWithFormat:#"%d",minDiff];
self.secondsLabel.text=[NSString stringWithFormat:#"%d",secDiff];
NSLog(#"\nDays: %i\nHours: %d\nMinutes: %i\nSeconds: %i",dayDiff,hourDiff,minDiff,secDiff);
Try this,
- (NSInteger)timeDifference:(NSDate *)fromDate ToDate:(NSDate *)toDate{
HMLogger_Info(#"<INPUT PARAMETERS> FromDate: %#, ToDate: %#",fromDate,toDate);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *differenceValue = [calendar components:NSHourCalendarUnit
fromDate:fromDate toDate:toDate options:0];
HMLogger_Info(#"Calculated hour difference : %d",[differenceValue hour]);
NSInteger hourDifference = [differenceValue hour];
HMLogger_Info(#"<RETURN VALUE>: HourDifference: %d",hourDifference);
return hourDifference;
}
Try this:
NSDate *dt2 = [[NSDate alloc]init];
NSString *dateStr=#"10/25/2013 11:22:33";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
dt2=[dateFormatter dateFromString:dateStr];
NSDate *dt1=[NSDate date];
NSUInteger unitFlags = NSDayCalendarUnit;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:unitFlags fromDate:dt1 toDate:dt2 options:0];
int i=[components day]+1;
int j=[components hour];
int k=[components minute];
NSLog(#"Days diff=%d, =%d, =%d",i,j,k);
I think it helps to youNSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];NSDateComponents *components = [calendar components:NSDayCalendarUnit|NSHourCalendarUnit fromDate:fromDate toDate:toDate options:0];NSLog(#"The difference between from date and to date is %d days and %d hours",components.day,components.hour);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *firstDate = #"2014-06-05 12:55:00";
NSDate *date=[dateFormatter dateFromString:firstDate];
NSDate *currentDate = [NSDate date];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:date toDate:currentDate options:0];
NSLog(#"The difference between from date and to date is %d days and %d hours and %d minute and %d second",components.day,components.hour,components.minute,components.second);
Output:
DateBookApp[1179:70b] The difference between from date and to date is 0 days and 22 hours and 57 minute and 12 Second

Cocoa get first day in week

How to get the first day of a week for a date
this seems more easy at it is, since :
when the week starts with sunday, i need to get back the sunday date
if it starts on monday, i need to get the monday date
the input date is any date in week with time... i tried several approaches, but the edge case make it difficould
i made a function, which however doesn't work in 100% (not sure about the [components setDay: -weekday + 2];)
- (NSDate *)firstDateOfWeek {
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
// because sunday is 0, we need it to be 6
NSInteger weekday = (([weekdayComponents weekday] + 6) % 7);
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
[components setDay: -weekday + 2];
return [calendar dateFromComponents:components];
}
It is easier to use the rangeOfUnit calendar method, which handles "start of the week" correctly according to the current locale:
NSDate *date = your date;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startOfWeek;
[calendar rangeOfUnit:NSWeekOfYearCalendarUnit
startDate:&startOfWeek
interval:NULL
forDate:date];
Using NSDateComponents, it would work as follows (assuming that a week has 7 days):
NSDate *date = your date;
NSDateComponents *comp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit
fromDate:date];
NSDate *startOfDay = [calendar dateFromComponents:comp];
NSInteger diff = (NSInteger)[calendar firstWeekday] - (NSInteger)[comp weekday];
if (diff > 0)
diff -= 7;
NSDateComponents *subtract = [[NSDateComponents alloc] init];
[subtract setDay:diff];
NSDate *startOfWeek = [calendar dateByAddingComponents:subtract toDate:startOfDay options:0];

Resources