Issue with calculating difference between two dates - iphone

I need to calculate difference between two days in minutes.
NSDate *now = [[NSDate alloc] init];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[outputFormatter setDateFormat:#"dd/MM/yyyy hh:mm:ss a"];
NSString* dateStringFromDatabase = #"01/01/1900 11:00:00 AM";
NSDate* dateFromString = [outputFormatter dateFromString:dateStringFromDatabase];
NSString* a = [outputFormatter stringFromDate:now];
NSDate* b = [outputFormatter dateFromString:a];
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:dateFromString
toDate:b options:0];
int hours = [components hour];
int minutes = [components minute];
self.lblResult.text = [NSString stringWithFormat:#"%i:%i", hours, minutes];
But I have the following issues:
For current hours I get:
2012-10-21 07:37:09 +0000 // wrong it's two hours late
When I try to cast #"01/01/1900 11:00:00 AM" to NSDate I get
1900-01-01 10:00:00 +0000 // also two hours late

Try This..................
if you have date in String then convert it into date using #"dd/MM/yyyy hh:mm:ss a"
NSDate *startDate = ...;
NSDate *endDate = ...;
Now Date comparison
// Date Comparision
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:LastDate
toDate:CuurentDate options:0];
Getting the difference between two dates
int months = [components month];
int days = [components day];
int hours = [components hour];
int minutes = [components minute];

You need to set the -dateStyle rather than the time style, as there is also a date contained in that string.
Edit---
You now need to change the -dateFormat to dd/MM/yyyy HH:mm:ss a

I hope this helps
NSString *dtString = #"1900-01-01T11:00:00";
dtString = [dtString stringByReplacingOccurrencesOfString:#"T" withString:#" "];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:today];
NSDate *toTimeDate = [dateFormatter dateFromString:dtString];
NSString *toTime = [dateFormatter stringFromDate:toTimeDate];

Related

NSDateFormatter not working to set setTimeZone

I am trying to know the difference between two dates (Including days,hours,minutes and seconds). For that I am using below code, but It's not working.
+ (void)UpdateTableViewCellWithNSTimer:(NSString *)gameTime :(UIView *)inputView{
NSDate *now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[NSLocale systemLocale]];
[outputFormatter setAMSymbol:#"AM"];
[outputFormatter setPMSymbol:#"PM"];
[outputFormatter setTimeZone:[NSTimeZone localTimeZone]];
[outputFormatter setDateFormat:#"mm/dd/yyyy hh:mm a"];
NSDate *gameDate = [outputFormatter dateFromString:gameTime];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:gameDate toDate:now options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
UITableView *dynamicTable = (UITableView *)[inputView viewWithTag:55];
NSIndexPath *cellIndexPath = [NSIndexPath indexPathForRow:4 inSection:0];
UITableViewCell *currentCell = [dynamicTable cellForRowAtIndexPath:cellIndexPath];
NSString *challengeStartsIn=[NSString stringWithFormat:#"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)];
NSString *Mystring =[NSString stringWithFormat:#"%# %#", #"ChallengeStartsIn", challengeStartsIn];
currentCell.textLabel.text = Mystring;
}
**Game and now dates on logs are:**
2013-05-18 11:36:42.609 FPPresent[2213:5203] gametime value=05/19/2013 5:30 AM
2013-05-18 11:36:42.610 FPPresent[2213:5203] now=2013-05-18 06:06:42 +0000
After using outputformatter:
gametime value =2013-01-19 00:00:00 +0000(It should be 2013-01-19 05:30:00 +0000 )
now=2013-05-18 06:10:07 +0000(should be : 2013-05-18 11:40:07 +0000)
The game date and now date should in localTimeZone. But, even I try to set
[outputFormatter setTimeZone:[NSTimeZone localTimeZone]];
My data format is showing (Exactly 5.30 hours different, our local time zone is GMT+5.30)
Please let me know where I am going wrong
[NSDate date] is taking default timezone as GMT. so, I am unable to set my local timezone to date.
While knowing the difference between GMT OFFset to local , I am able to get the difference between two dates sucessfully.
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setAMSymbol:#"AM"];
[outputFormatter setPMSymbol:#"PM"];
[outputFormatter setLocale:[NSLocale currentLocale]];
[outputFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *gameDate = [outputFormatter dateFromString:gameTime];
NSDate* gameDestinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:gameDate];
// NSLog(#"gameDate=%#",gameDate);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:destinationDate toDate:gameDestinationDate options:0];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger seconds = [components second];
NSInteger minutes = [components minute];
return ([NSString stringWithFormat:#"%01ddays:%02dhrs:%02dmins:%02dsec",abs(days),abs(hours), abs(minutes), abs(seconds)]);
Are you setting the timeZone for the output formatter and along with that are you adding the time difference to the output date?? Because, there is not need to add the time difference as setting timezone for both dateFormatters will automatically take care of the time difference between the time zones.

List days in calendar year

I am wanting to list (NSLog) all the dates of the Georgian calendar year (2013). I have managed to get the current date using the following:
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* components = [calendar components:NSDayCalendarUnit
fromDate:currDate];
NSInteger day = [components day];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(#"%#", dateString);
How can I print out all the dates in 2013?
NSDateFormatter* dateFormatter = [NSDateFormatter new] ;
dateFormatter.dateStyle = NSDateFormatterLongStyle ;
NSDate* today = [NSDate date] ;
NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] ;
NSDateComponents* thisYearComponents = [calendar components:NSYearCalendarUnit fromDate:today] ;
NSDate* firstDateInThisYear = [calendar dateFromComponents:thisYearComponents] ;
NSDateComponents* addDaysComponents = [NSDateComponents new] ;
addDaysComponents.day = 0 ;
while ( TRUE ) {
NSDate* nextDateInThisYear = [calendar dateByAddingComponents:addDaysComponents toDate:firstDateInThisYear options:0] ;
NSDateComponents* yearOfNextDateComponents = [calendar components:NSYearCalendarUnit fromDate:nextDateInThisYear] ;
if ( yearOfNextDateComponents.year == thisYearComponents.year )
NSLog(#"%#", [dateFormatter stringFromDate:nextDateInThisYear]) ;
else
break ;
addDaysComponents.day += 1 ;
}
The WWDC 2011 session 117 - Performing Calendar Calculations is a great source of information. It covers why it's better practice to, in a loop, add n days to a fixed reference date, rather than repeatedly adding 1 day to the most recently used date.
It also suggests using noon (12pm) instead of midnight (12am) for NSDates in which you don't care about the time, because Daylight Saving Time causes midnight to not exist for certain dates in certain places. But I didn't bother to do that in my example.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:#"2013-01-01"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:kCFCalendarUnitYear fromDate:date];
while ([components year] < 2014) {
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateStyle:NSDateFormatterLongStyle];
NSString *dateString = [dateFormatter1 stringFromDate:date];
NSLog(#"%#", dateString);
date = [NSDate dateWithTimeInterval:60*60*24 sinceDate:date];
components = [calendar components:kCFCalendarUnitYear fromDate:date];
}

Getting next date and previous day date

I basically want to convert a particular date (x) to the previous day date(x - 1 day) and also to the next day date (x + 1 day). I am using the following code for this :
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
However I have my date (x) in NSString format, and I need to convert the NSString(myDateString) to NSDate(myDate) before applying the above code.
I have a NSString containing date in format MM-dd-yyyy.
For converting I am using the following code , but I am getting absurd values.
NSLog(#"myDateString=%#",myDateString);//output:myDateString=10-25-2012//all correct
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-yyyy"];
NSDate *myDate=[formatter dateFromString:myDateString];
NSLog(#"myDate=%#",myDate);//output:myDate=2012-10-24 18:30:00 +0000 // I only want the date to be shown // and why has the format changed
NSDate *datePlusOneDay = [currentDate dateByAddingTimeInterval:(60 * 60 * 24)];
NSLog(#"datePlusOneDay=%#",datePlusOneDay);//output:datePlusOneDay=2012-10-25 18:30:00 +0000// I only want the date to come , not time // and why has the format changed
Later again I need to convert the NSDate to NSString
NSString *curentString=[formatter stringFromDate:datePlusOneDay];
NSLog(#"curentString=%#",curentString); //output:curentString=10-26-2012
Similarly I also want to get the previous date.
Please help guys !! and ho ho MERRY CHRISTMAS !!
Do as: componets.day = 1 to obtain the next, -1 for the previous day.
NSDate *date = [NSDate date]; // your date from the server will go here.
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
NSLog(#"newDate -> %#",newDate);
The below code should get you the previous date:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-1]; // replace "-1" with "1" to get the datePlusOneDay
NSDate *dateMinusOneDay = [gregorian dateByAddingComponents:offsetComponents toDate:myDate options:0];
Merry Xmas :)
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];
[components setHour:-[components hour]];
[components setMinute:-[components minute]];
[components setSecond:-[components second]];
NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight);
[components setHour:-24];
[components setMinute:0];
[components setSecond:0];
NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0];
Try this simple solution for previous date:-
NSDate *datePlusOneDay = [[NSDate date] dateByAddingTimeInterval:-(60 * 60 * 24)];
NSLog(#"datePlusOneDay=%#",datePlusOneDay);
Swift 5 Solution
let calendar = Calendar.current
calendar.date(byAdding: .day, value: -2, to: Date())
function for previousDay
-(void)previousDay
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
dateString = [dateFormat stringFromDate:today];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.day =-1;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
EndingDate = [dateFormat stringFromDate:sevenDays];
}
function for next day
-(void)nextDay
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
dateString = [dateFormat stringFromDate:today];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.day =1;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
[dateFormat setDateFormat:#"dd/MM/yyyy"];
EndingDate = [dateFormat stringFromDate:sevenDays];
}

Get time difference between two specific time zones in iPhone?

e.g. I want the time difference between asia/kolkata time and asia/dubai.
NSInteger differenceInSeconds = [timeZone1 secondsFromGMT] - [timeZone2 secondsFromGMT];
Note that this gives the current time difference between those timezones. If the two timezones observe daylight savings at different times of year, the time difference depends on when you evaluate this. If this matters to you, you should use secondsFromGMTForDate: to get the timezone offset at a specific date.
NSDate *now = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init] ;
[df setTimeStyle:NSDateFormatterFullStyle];
[df setTimeZone:[NSTimeZone timeZoneWithName:Str]];//str = timezone1(for you its kolkata)
[df setDateFormat:#"dd-MM-yyyy HH:mm"];
NSString *S1 = [df stringFromDate:now];
[df setDateFormat:#"dd-MM-yyyy HH:mm"];
NSDate *dd = [df dateFromString:S1];
//dd = date1 as per timezone
NSLog(#"dd > %#",dd);
[df release];
NSDate *dt = [NSDate date];
NSLog(#"dt = %#",dt);
NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
[df1 setTimeStyle:NSDateFormatterFullStyle];
[df1 setTimeZone:[NSTimeZone timeZoneWithName:Str2]];//str2=timezone2(for you its dubai)
[df1 setDateFormat:#"dd-MM-yyyy HH:mm"];
NSString *S2 = [df1 stringFromDate:dt];
[df setDateFormat:#"dd-MM-yyyy HH:mm"];
NSDate *dd1 = [df dateFromString:S2];
//dd1 = date2 as per timezone
NSLog(#"dd1 > %#",dd1);
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:dd toDate:dd1 options:0];
NSLog(#"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);
i'm usin this code and its working properly.

iphone NSDate - get todays date and force the time

hopefully a quick one for someone! I am struggling to see why the code below isn't working. I am trying to get today's date (eg: 2010-09-10) and manually adding the time. It always seems to return 00:00:00 for the time though. any ideas where I'm going wrong?
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSString *actualDate = [dateFormatter stringFromDate:[NSDate date]];
NSDate *sDate = [dateFormatter dateFromString:[NSString stringWithFormat:#"%# %#", actualDate, #"01:00:00"]];
NSDate *eDate = [dateFormatter dateFromString:[NSString stringWithFormat:#"%# %#", actualDate, #"23:59:59"]];
The NSDate objects are returning the format 2010-09-10 00:00:00 +01:00 all the time. Somewhere it's just not picking up the time.... any ideas? many thanks.
* UPDATE *
The code below works. I did as suggested and accessed the elements and updated them.
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = #"yyyy-MM-dd hh:mm:ss";
//update for the start date
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate *sDate = [calendar dateFromComponents:comps];
//update for the end date
[comps setHour:23];
[comps setMinute:59];
[comps setSecond:59];
NSDate *eDate = [calendar dateFromComponents:comps];
You should use NSCalendar instead then. It allows you to parse the current date and modify its components. Like you can initialize it with today's date and then set the time and then get an NSDate from it.
(Old answer: Because your formatter is configured to only recognize the date part. Add the time part to it (even though its name is NSDateFormatter, it will happily parse dates and times) and you will see the time too.)
I found this question today while looking to do the same thing, create an NSDate with a specific time today. The solution presented wasn't quite what I needed so I came up with this:
NSDate * date;
NSString * string, *timestamp;
NSDateFormatter * formatter;
timestamp = #"17:30";
formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat: #"yyyy-MM-dd "];
[formatter setTimeZone: [NSTimeZone localTimeZone]];
string = [formatter stringFromDate: [NSDate date]];
string = [string stringByAppendingString: timestamp];
[formatter setDateFormat: #"yyyy-MM-dd HH:mm"];
date = [formatter dateFromString: string];