Compare Date object? - ios

I have this date object from Parse, "2015-07-24 20:36:38 +0000" and I would like to compare it to today's date to see how much time has passed since the date on the date object. Any ideas how to do this?
I have this method I use to get the hour and minute, but I'm stuck on how to use this to compare dates outside of the current day.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm"];
NSString *formattedTime = [dateFormatter stringFromDate: date];

You can use an NSTimeInterval for this, the code is:
NSTimeInterval timeInterval = [date timeIntervalSinceNow];
with date being the date from parse as an NSDate, not NSString. and there should be no need to format it before comparing. Hope this helps

If you want this formatted as a string, in iOS 8 and later you can use NSDateComponentsFormatter:
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitHour;
NSString *string = [formatter stringFromDate:date toDate:[NSDate date]];

Related

Format date to secounds

Background: I have dates stored in files.
What I would like to do: I would like to take the difference between two dates in seconds. I can't find any way to do it. My date format looks like that:
2015-23-02-12-23-43
Try this out:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-mm-dd-hh-mm-ss"];
NSDate *date = [dateFormatter dateFromString:string1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
Try this:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:EnterYourStringHere];
NSString *str = [dateFormatter stringFromDate:date];
If all you need is seconds then use
NSTimeInterval dateInterval = [date timeIntervalSince1970];
Then
NSString secondsString = [NSString stringWithFormat: #"%.0f", dateInterval];
EDIT:
If you have a file full of date strings that look like your example, 2015-23-02-12-23, then you could use code like this:
NSDateFormatter *myFormatter = [[NSDateFormatter alloc] init];
[myFormatter setDateFormat:#"yyyy-mm-dd-hh-mm-ss"];
//an example - you'll read from your file
NSString *aDateString = #"2015-23-02-12-23";
NSDate aDate = [myFormatter dateFromString: aDateString];
NSTimeInterval dateSeconds = [aDate timeIntervalSince1970];
That will give you dateSeconds as a double precision floating point number, which is the norm for numeric date calculations since it deals with fractions of seconds. You can then do numeric comparisons of date's time intervals.
Note that most UNIX systems use the numeric values returned by the timeIntervalSince1970 method, but Mac and iOS uses numeric date values returned by the method timeIntervalSinceReferenceDate. The two methods have different "epoch dates", or dates where they start counting from zero.
timeIntervalSince1970 uses midnight on Jan 1, 1970 (GMT)
timeIntervalSinceReferenceDate uses midnight on Jan 1, 2001 (GMT)
Which you use is up to you, just be sure to use the same method in all cases.
By the way, your date string format is horrible. having all those 2 digit numbers separated by dashes doesn't give the reader any way to tell apart month/day/hours/minutes/seconds. It's all a jumble. You'd be much better off using a standard date format.
In the US it's common to display dates in the form mm/dd/yyyyy (or yyyy/mm/dd, or even yyyy/dd/mm), and times as hh:mm:ss, so in "mm/dd/yyyyy hh:mm:ss" format you'd get:"09/02/2015 13:09:39" (I'm using human-readable date format strings for discussion, not those intended to set up a date formatter.)

How to get and convert back user's birthdate to/from a NSTimeInterval?

Suppose, my birthdate is (mon/day/year) 10-05-1932 (as NSDate), how to convert this to NSTimeInterval.
Again, how to convert back that NSTimeInterval to NSDate back?
I tried using different methods of NSDate but haven't succeed yet.
What I'm doing?
NSString *strdate = #"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(#"%.f", -[date timeIntervalSinceNow]);
This logs 2616605071 (as on 4th September 2015 at 16:21) – When I checked it with the site like this it gives me wrong date.
NSTimeInterval timeInterval = date.timeIntervalSinceReferenceDate;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate: timeInterval];
Try the code below. date and anotherDate will be identical.
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:10];
[components setMonth:5];
[components setYear:1934];
NSDate *date = [calendar dateFromComponents:components];
NSLog(#"%#", date);
NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
NSDate *anotherDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
NSLog(#"%#", anotherDate);
UPDATE:
It's incorrect because you get timestamp (time interval) from that website which use UNIX timestamp. Also, it's incorrect because you use timeIntervalSinceNow which will likely change every time you call the method because it's relative to the current time. If you want the date/time interval that compatible with that website. Use:
NSTimeInterval timeInterval = date.timeIntervalSince1970;
NSDate *anotherDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
You can copy the timeInterval from the code above (-1188000000) and paste it on the website and it will give you a correct date.
Internally, NSDate store time interval relative to reference date (Jan 1st, 2001). The website you mentioned is UNIX timestamp that relative to Jan 1st, 1970.
This is just worked!
NSString *strdate = #"10-05-1932";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM-dd-yyyy"];
NSDate *date = [df dateFromString:strdate];
NSLog(#"%#",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(#"%f", interval);
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:interval];
NSLog(#"%#",date2);
Thanks to #sikhapol

Get the difference time between two NSString in Objective C

I have two strings coming from my server in which I store the time, and I need to compare the time interval between those two, in minutes, and if it's necessary, in hours. Should I convert to NSDate or use NSString?
The NSStrings look like:
NOW 14:22
LAST TIME 10:18
EDIT #1
Since everyone is saying me to use NSDate, i converted the data in my database to DATETIME, and now i can compare the two NSDate using the following code :
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"pt_BR"]];
[dateFormatter setDateFormat: #"yyyy-MM-dd HH:mm:ss"];
NSDate *currentDateTimeWithOffset = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];
NSString *strDate = [dateFormatter stringFromDate:currentDateTimeWithOffset];
NSDate * now = [dateFormatter dateFromString:strDate];
NSDate *date = [dateFormatter dateFromString:#"2013-04-09 12:10:18"];
NSLog(#"Difference %f",[now timeIntervalSinceDate:date]);
And the result is the following :
Difference 864.000000
NOW 2013-04-09 15:24:42 +0000
LAST DATE 2013-04-09 12:10:18
Is that correct? the Difference is in Seconds?
If the format gets more complex than the one you've shown, consider using NSDateFormatter. For the simple example:
NSArray *hoursMins = [timeString componentsSeparatedByString:#":"];
NSInteger timeInMins = [hoursMins[0] intValue] * 60 + [hoursMins[1] intValue];
Then subtract the two times in minutes. The date formatter approach looks like this:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
NSDate *date = [df dateFromString:timeString];
You can get a difference in seconds between two dates using:
[date timerIntervalSinceDate:anotherDate];
NSDateFormatter is the "clean" way to do it. But if you are looking for quick and dirty, and those are the actual strings you are getting (that include the NOW and LAST TIME), I'd just use a specific NSRange to pull the hours and minutes out and compare them.
Make sure, though that you check the hours, and if the "now" hour is before the "last time" hour, you add 24 to the now to throw in the day rollover.
With only NSString, NSDateFormatter is used to get NSDate
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
If you had separate values for hours, minutes and seconds you could use NSCalendar
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1965];
[comps setMonth:1];
[comps setDay:6];
[comps setHour:14];
[comps setMinute:10];
[comps setSecond:0];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
And a perfect solution would be to use timestamps instead of NSString. Not only it's easy to convert timestamps to NSDate (NSDate +dateWithTimeIntervalSinceReferenceDate)and then to NSString when needed, but you can also get the time difference by subtraction.
And with two NSDate objects the time difference is calculated with NSDate -timeIntervalSinceDate.

NSDate format not showing what expected

I have problems printing a date as NSString. I have stored current date and time at certain points of my app lifecycle this way:
NSDate *current = [NSDate date];
long currentTime = [current timeIntervalSince1970];
Now, I need to show those dates in UILabels. I tried this way:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:currentTime];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy - HH:mm:ss"];
NSString *stringFromDate = [formatter stringFromDate:date];
but I'm not getting the correct date nor the time. What could I be missing?
Thanks!
Try this,
NSString *stringFromDate=[NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
also you can change the datestyle and timestyle.
Your currentTime variable is a long, and not an NSTimeInterval (a double). You are losing not only the fractional part (less important), but the upper range of the time interval. Change it to:
NSTimeInterval currentTime = [current timeIntervalSince1970];

How to compare current date to previous date in iphone?

I would like to compare the current date with another date, and if that is date is earlier than the current date, then I should stop the next action. How can I do this?
I have todays date in yyyy-MM-dd format. I need to check this condition
if([displaydate text]<currentdate)
{
//stop next action
}
Here if displaydate is less than todays date then it has to enter that condition.
NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [dateFormatter dateWithString:#"xxxxxx"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:newDate]; // comparing two dates
if(result==NSOrderedAscending)
NSLog(#"today is less");
else if(result==NSOrderedDescending)
NSLog(#"newDate is less");
else
NSLog(#"Both dates are same");
got your solution from this answer How to compare two dates in Objective-C
Alternative to #NNitin Gohel's answer.
Compare using NSTimeInterval ie NSDate timeIntervalSince1970:
NSTimeInterval *todayTimeInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval *previousTimeInterval = [previousdate timeIntervalSince1970];
if(previousTimeInterval < todayTimeInterval)
//prevous date is less than today
else if (previousTimeInterval == todayTimeInterval)
//both date are equal
else
//prevous date is greater than today
You can have a closer look at this Tutorial about NSDateFormatter and when you have your NSDate object you can compare it to another NSDate and get an NSTimeInterval which is the difference in seconds.
NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];
Some methods of NSDate class are:
isEarlierThanDate. // using this method you can find out the date is previous or not..
isLaterThanDate
minutesAfterDate.
minutesBeforeDate. etc..
also see this link with many methods of NSDate in iPhone SDK..
how-to-real-world-dates-with-the-iphone-sdk
Update
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
use this bellow method for convert NSString date to NSDate format just paste this method in your.m file
- (NSDate *)convertStringToDate:(NSString *) date {
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd"];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", date);
date = [date stringByReplacingOccurrencesOfString:#"+0000" withString:#""];
nowDate = [formatter dateFromString:date];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", nowDate);
return nowDate;
}
after that when you want to use it just use like bellow..
NSDate *tempDate2 = [self convertStringToDate:yourStringDate];
and then try to compare like this..
if (tempDate2 > nowDate)

Resources