Issue with NSDate - ios

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]);

Related

Addition of two NSDate in Objective-C

I have two NSDates with this format : "H.m.s" and I want to do an addition of this two dates to compare the result with my current time on my phone.
I have all the information as you can see bellow :
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"H:m:s"];
NSDate *start = [dateFormat dateFromString:NextTVS.startTime];
NSDate *duration = [dateFormat dateFromString:NextTVS.duration];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
[calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
However I don't know how to add start and duration.
Thanks for your help
Use the dateByAddingComponents method of the NSCalendar class like so:
NSDateComponents *comps = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
NSDate *newDate = [calendar dateByAddingComponents: comps toDate: date options:0];

Month value coming wrong for a specified date?

Following is my code:
NSDateComponents *componenetsForEnd = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:endDate];
NSInteger endDay = [componenetsForEnd day];
NSInteger endMonth = [componenetsFoeEnd month];
NSInteger endDayValue = componenetsForEnd.weekday;
Now: when endDate = 2015-08-31 23:59:59 +0000, I am getting month as 9! This is causing wrong endDayValue. What is going wrong here?
EDIT:
Here is how I calculate endDate :
NSDate *endDate = [self endOfMonthForDate:todayDate];
this method takes today's date with [NSDate date] and this is how it goes:
- (NSDate *) dateByAddingMonths: (NSInteger) monthsToAdd andDate: (NSDate *)date
{
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents * months = [[NSDateComponents alloc] init];
[months setMonth: monthsToAdd];
return [calendar dateByAddingComponents: months toDate: date options: 0];
}
- (NSDate *) endOfMonthForDate: (NSDate *)date
{
NSCalendar * calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone systemTimeZone]];
NSDate * plusOneMonthDate = [self dateByAddingMonths: 1 andDate:date];
NSDateComponents * plusOneMonthDateComponents = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit fromDate: plusOneMonthDate];
NSDate * endOfMonth1 = [[calendar dateFromComponents: plusOneMonthDateComponents] dateByAddingTimeInterval: -1]; // One second before the start of next month
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:endOfMonth1];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:endOfMonth1];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* endOfMonth = [[NSDate alloc] initWithTimeInterval:interval sinceDate:endOfMonth1];
return endOfMonth;
}
Also tried performing these actions to make NSDateComponents and NSDate with dateFormatter in systemTimeZone:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSString *endDateString = [dateFormatter stringFromDate:endDate];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
[dateFormatter2 setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter2.dateFormat = #"yyyy-MM-dd HH:mm:ss";
NSDate *endDateProper = [dateFormatter2 dateFromString:endDateString];
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componenetsForEnd = [greCalendar components:NSWeekdayCalendarUnit | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:endDateProper];
[componenetsForEnd setTimeZone:[NSTimeZone systemTimeZone]];
Instead of using current calendar
[NSCalendar currentCalendar]
you can use:
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
The problem was with the fact that I think is this way: When calculating a day, month or Hour, minute and second , you need to specify that timezone for dateComponents is UTC i.e. GMT. However, my endDateProper which is in system timezone.
So, doing this did the trick for me:
NSDateComponents *componenetsForEnd = [greCalendar componentsInTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"] fromDate:endDateProper];

dateFromComponents returning wrong value

I'm trying to set the month and year of [NSDate date] but the function dateFromComponents return the wrong value, this is my code:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian]; // Setup an NSCalendar
NSDateComponents *components = [gregorianCalendar components: NSUIntegerMax fromDate: [NSDate date]]; // Setup NSDateComponents
[components setTimeZone:[NSTimeZone defaultTimeZone]];
[components setMonth:monthInt];
[components setYear:yearInt];
// Setup the new date
NSDate *dateToCompare = [gregorianCalendar dateFromComponents: components];
yearInt is 2014 and monthInt is 12, but it reports back 12-2015 and not 2014, why is this?
Thanks!
you need to put only the bit operator you need, try this:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian]; // Setup an NSCalendar
NSDateComponents *components = [gregorianCalendar components: NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear |NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitTimeZone fromDate: [NSDate date]]; // Setup NSDateComponents
[components setTimeZone:[NSTimeZone defaultTimeZone]];
[components setMonth:12];
[components setYear:2014];
// Setup the new date
NSDate *dateToCompare = [gregorianCalendar dateFromComponents: components];
NSLog(#"Ver %#",dateToCompare);
NSUIntegerMax = 18446744073709551615
In bit representation: 10000000000000000000000000000000000000000000000000000000000000000
To many switch off.

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)

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

Resources