How to Determine If an Nsdate Is Today

How to determine if an NSDate is today?

In macOS 10.9+ & iOS 8+, there's a method on NSCalendar/Calendar that does exactly this!

- (BOOL)isDateInToday:(NSDate *)date 

So you'd simply do

Objective-C:

BOOL today = [[NSCalendar currentCalendar] isDateInToday:date];

Swift 3:

let today = Calendar.current.isDateInToday(date)

Find out if an NSDate is today, yesterday, tomorrow

Check our Erica Sadun's great NSDate extension class: http://github.com/erica/NSDate-Extensions

There are lots of date comparisons, among them exactly what you need :)

How to determine if NSDate is today

The problem is that you have written the name of the components: parameter as component:. Those are not the same thing, as you should know if you are an "experienced C programmer" - just as two variables called thing and things are not the same.

If you correct that error, then your change to modernize the names of the components will compile just fine, without any warnings:

+ (BOOL) isToday:(NSDate *)aDate {
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:[NSDate date]];
NSDate *today = [cal dateFromComponents:components];
components = [cal components:(NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay) fromDate:aDate];
NSDate *otherDate = [cal dateFromComponents:components];
BOOL isToday = [today isEqualToDate:otherDate];
return isToday;
}

How to check if NSDate is in current week?

I had to replace NSWeekCalendarUnit with NSCalendarUnitWeekOfYear

- (NSInteger)thisW:(NSDate *)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:date];
NSUInteger datesWeek = [otherComponents weekOfYear];

//NSLog(@"Date %@",date);
if(todaysWeek==datesWeek){
//NSLog(@"Date is in this week");
return 1;
}else if(todaysWeek+1==datesWeek){
//NSLog(@"Date is in next week");
return 2;
} else {
return 0;
}

}

Check whether NSDate is Monday/Tues/etc

You can use following program.

NSDateComponents *component = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]];

switch ([component weekday]) {
case 1:
//Sunday
break;
case 2:
//Monday
break;
...
case 7:
//Saturday
break;
default:
break;
}

Swift - check if a timestamp is yesterday, today, tomorrow, or X days ago

Calendar has methods for all three cases

func isDateInYesterday(_ date: Date) -> Bool
func isDateInToday(_ date: Date) -> Bool
func isDateInTomorrow(_ date: Date) -> Bool

To calculate the days earlier than yesterday use

func dateComponents(_ components: Set<Calendar.Component>, 
from start: Date,
to end: Date) -> DateComponents

pass [.day] to components and get the day property from the result.


This is a function which considers also is in for earlier and later dates by stripping the time part (Swift 3+).

func dayDifference(from interval : TimeInterval) -> String
{
let calendar = Calendar.current
let date = Date(timeIntervalSince1970: interval)
if calendar.isDateInYesterday(date) { return "Yesterday" }
else if calendar.isDateInToday(date) { return "Today" }
else if calendar.isDateInTomorrow(date) { return "Tomorrow" }
else {
let startOfNow = calendar.startOfDay(for: Date())
let startOfTimeStamp = calendar.startOfDay(for: date)
let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
let day = components.day!
if day < 1 { return "\(-day) days ago" }
else { return "In \(day) days" }
}
}

Alternatively you could use DateFormatter for Yesterday, Today and Tomorrow to get localized strings for free

func dayDifference(from interval : TimeInterval) -> String
{
let calendar = Calendar.current
let date = Date(timeIntervalSince1970: interval)
let startOfNow = calendar.startOfDay(for: Date())
let startOfTimeStamp = calendar.startOfDay(for: date)
let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
let day = components.day!
if abs(day) < 2 {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .none
formatter.doesRelativeDateFormatting = true
return formatter.string(from: date)
} else if day > 1 {
return "In \(day) days"
} else {
return "\(-day) days ago"
}
}

Update:

In macOS 10.15 / iOS 13 RelativeDateTimeFormatter was introduced to return (localized) strings relative to a specific date.

Swift - How to check if an NSDate is yesterday compare to current time?

As of iOS 8.0, you can use -[NSCalendar isDateInYesterday:], like this:

let calendar = NSCalendar.autoupdatingCurrentCalendar()

let someDate: NSDate = some date...
if calendar.isDateInYesterday(someDate) {
// It was yesterday...
}

If you'll be doing this a lot, you should create the calendar once and keep it in an instance variable, because creating the calendar object is not trivial.

How to check if two NSDates are from the same day

NSCalendar has a method that does exactly what you want actually!

/*
This API compares the Days of the given dates, reporting them equal if they are in the same Day.
*/
- (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2 NS_AVAILABLE(10_9, 8_0);

So you'd use it like this:

[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2];

Or in Swift

Calendar.current.isDate(date1, inSameDayAs:date2)

Check if date is before current date (Swift)

I find the earlierDate method.

if date1.earlierDate(date2).isEqualToDate(date1)  {
print("date1 is earlier than date2")
}

You also have the laterDate method.

Swift 3 to swift 5:

if date1 < date2  {
print("date1 is earlier than date2")
}

Trying to determine if current date is 3 days or less from the end of the month in iOS

First you have to compute the start of the current day (i.e. today at 00.00).
Otherwise, the current day will not count as a full day when computing the
difference between today and the start of the next month.

NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startOfToday;
[cal rangeOfUnit:NSCalendarUnitDay startDate:&startOfToday interval:NULL forDate:now];

Computing the start of the next month can be done with rangeOfUnit:...
(using a "statement expression" to be fancy :)

NSDate *startOfNextMonth = ({
NSDate *startOfThisMonth;
NSTimeInterval lengthOfThisMonth;
[cal rangeOfUnit:NSCalendarUnitMonth startDate:&startOfThisMonth interval:&lengthOfThisMonth forDate:now];
[startOfThisMonth dateByAddingTimeInterval:lengthOfThisMonth];
});

And finally the difference in days:

NSDateComponents *comp = [cal components:NSCalendarUnitDay fromDate:startOfToday toDate:startOfNextMonth options:0];
if (comp.day < 4) {
// ...
}


Related Topics



Leave a reply



Submit