How to compare two dates in iOS [duplicate] - ios

This question already has answers here:
iOS: Compare two dates
(6 answers)
Closed 9 years ago.
I want to compare two dates.This my code i wrote
NSDate *c_date=[NSDate date];
NSDate *newDate = [c_date dateByAddingTimeInterval:300];
This code is not working?What i am missing?

From NSDate, you can use
- (NSComparisonResult)compare:(NSDate *)anotherDate

You can use
- (NSComparisonResult)compare:(NSDate *)other;
which will yield a
typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};
in your example you're just creating two different NSDate objects with a known NSTimeInterval (300), so there is no comparison.

Use [NSDate timeIntervalSince1970] which will return a simple double value that can be used for comparison just like any other.
NSDate *c_date=[NSDate date];
NSDate *newDate = [c_date dateByAddingTimeInterval:300];
NSTimeInterval c_ti = [c_date timeIntervalSince1970];
NSTimeInterval new_ti = [newDate timeIntervalSince1970];
if (c_ti < new_ti) {
// c_date is before newDate
} else if (c_ti > new_ti) {
// c_date is after newDate
} else {
// c_date and newDate are the same
}
There are also the [NSDate compare:] method, that you might find more convenient.

Here's the thing (well, it might be the thing, it's not completely 100% clear from your question). NSDate represents an interval in seconds since 1st January 1970. Internally, it uses a floating point number (a double in OS X, not sure in iOS). This means that comparing two NSDates for equality is dry hit and miss, actually it's mostly miss.
If you want to make sure one date is within, say, 1/2 a second of another date, try:
fabs([firstDate timeIntervalSinceDate: secondDate]) < 0.5
If you just want both dates to be on the same day, you'll need to muck about with NSCalendar and date components.
See also this SO answer.
https://stackoverflow.com/a/6112384/169346

Related

Notify when device date enters a date range on iOS [duplicate]

I am interested in creating a method to find if the current date falls between certain times on any given day. It is for a scheduling program, so I want to find what event is occurring at the current time. Every day has the same set of times: 820-900, 900-940, 940-1020, etc. Since this must be done on any given day I do not know how to create an NSDate with a certain time. I think this might be done with NSTimeInterval but I am not sure how to instantiate that.
This isn't perfect, but you could use [NSDate compare:] to check your date against both boundaries:
NSDate *firstDate = ...
NSDate *secondDate = ...
NSDate *myDate = [NSDate date];
switch ([myDate compare:firstDate]) {
case NSOrderedAscending:
NSLog(#"myDate is older");
// do something
break;
case NSOrderedSame:
NSLog(#"myDate is the same as firstDate");
// do something
break;
case NSOrderedDescending:
NSLog(#"myDate is more recent");
// do something
break;
}
switch ([myDate compare:secondDate]) {
case NSOrderedAscending:
NSLog(#"myDate is older");
// do something
break;
case NSOrderedSame:
NSLog(#"myDate is the same as secondDate");
// do something
break;
case NSOrderedDescending:
NSLog(#"myDate is more recent");
// do something
break;
}
Or more briefly:
BOOL between = NO;
if (([myDate compare:firstDate] == NSOrderedDescending) &&
([myDate compare:secondDate] == NSOrderedAscending)) {
between = YES;
}
I'm sure there's a better way to do complex date comparison, but this should work.
The easiest way to do this would be to use -timeIntervalSinceReferenceDate to turn each of your dates into an NSTimeInterval typed value, which is really just a double.
NSTimeInterval rightNow = [[NSDate date] timeIntervalSinceReferenceDate];
From there, determining if a date is in between any given two dates is just a matter of simple numeric comparisons.
If you need to convert from a string representation of a date to an NSDate instance to then retrieve a time interval, use NSDateFormatter.
If you need to create a date from known date components, use NSCalendar. (i.e. you know the year is 2010, the month is 4 and the day is 12, you can use NSCalendar's components to generate an NSDate instance via the -dateFromComponents: method.).
As Ben indicated, NSCalendar's component interface can also be used to suss out the hour & minute to determine if it is in a range (which would seemingly be an atypical usage in that most events don't happen every day at the same time... but... sure... there are reasons to do that, too!)
Take a look at -[NSCalendar components:fromDate:]. It will let you 'decompose' a date into its various components, and then you can, in this instance, look at the hour and minute.

How would I be able to convert the date into an integer?

I need to be able to convert the date of the day to an integer so that I can then save it as an integer to use in other areas in my code. I know that there are other ways to save a date in Xcode, but for this specific problem I need to use it as an integer. So my over all question is how would I be able to convert the date into an integer so that I can then use that integer in an NSString? Thanks in advance!
You can do that by using the timeIntervalSinceReferenceDate method.
// Get time from baseline date to now as a double.
double interval = [[NSDate date] timeIntervalSinceReferenceDate];
// Re-apply the time value
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:interval];
Reference date is a base line date that will always have the same value. So you can safely use it as a reference point. Then you just store the NSTimeInterval (typedef to double) between the reference date and now. That gives you the number of seconds that has taken place between the reference date and now.
Edit:
As mentioned in the comments, if your date is eArlier than 2001, you can use the 1970 reference date.
// Get time from baseline date to now as a double.
double interval = [[NSDate date] timeIntervalSince1970];
// Re-apply the time value
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
If your dates are later than 2001, either method will work for you.
You may convert from double to integer using
int interval = (int)[[NSDate date] timeIntervalSince1970];
Since the double will be truncated to the nearest second, you will want to decide if you want to round up or down. Leaving as is will round down. You can round to the proper nearest second by using:
interval = round(interval);

ios minutes to time

I want to go from minutes as an int (eg 92) to a string of 1:32. Is there a fancy way to do this using objc or I'm I stuck with figuring it out the old-fashioned way?
I do not believe there is a function to do this, but it is simple enough to do on your own.
int hour = minutes / 60;
int min = minutes % 60;
NSString *timeString = [NSString stringWithFormat: %#"%d:%02d", hour, min];
The '02' will pad the results so there are always two digits in the minutes place. It may be useful to look at the NSDate Class Reference as it may save you time if you want to do calculations on the result.
I think you can find the answer here: NSTimeInterval to NSDate
The int you talking about should be NSTimeInterval (that is just double), convert it to a NSDate object and then format it using the NSDateFormatter with: HH:mm.
It can also could be more useful "extend" using categories NSDate object
#interface NSDate (Minutes)
and put there a method convert minutes to HH:mm (maybe could be better to move the format string as method parameter) so you never more need think about it.

NSDate - Convert Date to GMT

I need the ability to convert an NSDate value to a GMT Date.
How can I go about converting an NSDate value to a GMT formatted NSDate value, independent of whatever date locale settings the iPhone device is using?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH:mm";
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
Working with time in Cocoa can be complicated. When you get an NSDate object, it's in the local time zone. [[NSTimeZone defaultTimeZone] secondsFromGMT] gives you the offset of the current time zone from GMT. Then you can do this:
NSDate *localDate = // get the date
NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; // You could also use the systemTimeZone method
NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];
Now gmtDate should have the correct date in GMT for you. In order to display it, look at NSDateFormatter, specifically the setDateStyle and setTimeStyle methods. You create an NSDateFormatter, configure it the way you want, and then call stringFromDate: to get a nicely formatted string.
Howard's Answer is correct and please vote it up and accept it.
For reference I think it is useful to explain the difference between date objects and localised date representations are.
In many programming languages date objects are used to represent unique points in time. Ignoring Relativistic arguments it can be assumed that at any instance we can define a point in time which is equal universally for every one, regardless of how we measure time.
If for each point in time we could construct a unique label, that label could be passed around and referenced unambiguously. The purpose of date objects is to act as a unique universal label for a given point in time.
One could come up with any number of techniques to construct such a labelling scheme and how each date object chooses to do so is immaterial to anyone using them.
An example may be to use a numeric offset from a universal event (X seconds since the sun exploded).
It is only when we wish to take a time point and serialize it into a human readable string that we must deal with the complexities of time zones, locales, etc...
(Local Date String) + (Date Formatter) => Time Point
Time Point + (Date Formatter) => (Local Date String)
Every time point is universal... there is no such thing as a new york time point, or gmt time point, only once you convert a time point to a local string (using a date formatter) does any association to a time zone appear.
Note: I'm sure there are many blogs/articles on this very issue, but my google foo is failing me at this hour. If anyone has the enthusiasm to expand on this issue please feel free to do so.
Swift 4:
//UTC or GMT ⟺ Local
extension Date {
// Convert local time to UTC (or GMT)
func toGlobalTime() -> Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
}
While Alex's answer was a good start, it didn't deal with DST (daylight savings time) and added an unnecessary conversion to/from the reference date. The following works for me:
To convert from a localDate to GMT, taking DST into account:
NSDate *localDate = <<your local date>>
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:localDate];
NSDate *gmtDate = [localDate dateByAddingTimeInterval:-timeZoneOffset]; // NOTE the "-" sign!
To convert from a GMT date to a localDate, taking DST into account:
NSDate *gmtDate = <<your gmt date>>
NSTimeInterval timeZoneOffset = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:gmtDate];
NSDate *localDate = [gmtDate dateByAddingTimeInterval:timeZoneOffset];
One small note: I used dateByAddingTimeInterval, which is iOS 4 only. If you are on OS 3 or earlier, use addTimerInterval.
Have you tried looking at the documentation for NSDateFormatter?
NSDateFormatter
NSDateFormatter appears to have some methods for playing with TimeZones, particularly
-setTimeZone:
I haven't tested it myself, but I imagine that if you set GMT as the timezone on a date that is originally represented in another timezone, it will display the date with the correct adjustments to match the new timezone.

How to set seconds to zero for NSDate

I'm trying to get NSDate from UIDatePicker, but it constantly returns me a date time with trailing 20 seconds. How can I manually set NSDate's second to zero?
NSDate is immutable, so you cannot modify its time. But you can create a new date object that snaps to the nearest minute:
NSTimeInterval time = floor([date timeIntervalSinceReferenceDate] / 60.0) * 60.0;
NSDate *minute = [NSDate dateWithTimeIntervalSinceReferenceDate:time];
Edit to answer Uli's comment
The reference date for NSDate is January 1, 2001, 0:00 GMT. There have been two leap seconds added since then: 2005 and 2010, so the value returned by [NSDate timeIntervalSinceReferenceDate] should be off by two seconds.
This is not the case: timeIntervalSinceReferenceDate is exactly synchronous to the wall time.
When answering the question I did not make sure that this is actually true. I just assumed that Mac OS would behave as UNIX time (1970 epoch) does: POSIX guarantees that each day starts at a multiple of 86,400 seconds.
Looking at the values returned from NSDate this assumption seems to be correct but it sure would be nice to find a definite (documented) statement of that.
You can't directly manipulate the NSTimeInterval since that is the distance in seconds since the reference date, which isn't guaranteed to be a 00-second-time when divided by 60. After all, leap seconds may have been inserted to adjust for differences between solar time and UTC. Each leap second would throw you off by 1. What I do to fix the seconds of my date to 0 is:
NSDate * startDateTime = [NSDate date];
NSDateComponents * startSeconds = [[NSCalendar currentCalendar] components: NSSecondCalendarUnit fromDate: startDateTime];
startDateTime = [NSDate dateWithTimeIntervalSinceReferenceDate: [startDateTime timeIntervalSinceReferenceDate] -[startSeconds second]];
This takes care of leap seconds. I guess an even cleaner way would be to use -dateByAddingComponents:
NSDate * startDateTime = [NSDate date];
NSDateComponents * startSeconds = [[NSCalendar currentCalendar] components: NSSecondCalendarUnit fromDate: startDateTime];
[startSeconds setSecond: -[startSeconds second]];
startDateTime = [[NSCalendar currentCalendar] dateByAddingComponents: startSeconds toDate: startDateTime options: 0];
That way you're guaranteed that whatever special things -dateByAddingComponents: takes care of is accounted for as well.
Here is a Swift extension for anyone who is interested:
extension Date {
public mutating func floorSeconds() {
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: self)
self = calendar.date(from: components) ?? self // you can handle nil however you choose, probably safe to force unwrap in most cases anyway
}
}
Example usage:
let date = Date()
date.floorSeconds()
Using DateComponents is much more robust than adding a time interval to a date.
Although this is an old question and Uli has given the "correct" answer, the simplest solution IMHO is to just subtract the seconds from the date, as obtained from the calendar. Mind that this may still leave milliseconds in place.
NSDate *date = [NSDate date];
NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSCalendarUnitSecond
fromDate:date];
date = [date dateByAddingTimeInterval:-comp.second];
NSDate records a single moment in time. If what you want to do is store a specific day, don't use NSDate. You'll get lots of unexpected head-aches related to time-zones, daylight savings time e.tc.
One alternative solution is to store the day as an integer in quasi-ISO standard format, like 20110915 for the 15th of September, 2011. This is guaranteed to sort in the same way as NSDate would sort.
Here is an extension to do this in Swift:
extension NSDate {
func truncateSeconds() -> NSDate {
let roundedTime = floor(self.timeIntervalSinceReferenceDate / 60) * 60
return NSDate(timeIntervalSinceReferenceDate: roundedTime)
}
}
Also Swift ...
extension Date {
func floored() -> Date {
let flooredSeconds = DateComponents(second: 0, nanosecond: 0)
return Calendar.current.nextDate(after: self,
matching: flooredSeconds,
matchingPolicy: .strict,
direction: Calendar.SearchDirection.backward)!
}
}

Resources