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.
Is a date in same week, month, year of another date in swift
You can use calendar method isDate(equalTo:granularity:)
to check it as follow:
Xcode 11 • Swift 5.1
extension Date {
func isEqual(to date: Date, toGranularity component: Calendar.Component, in calendar: Calendar = .current) -> Bool {
calendar.isDate(self, equalTo: date, toGranularity: component)
}
func isInSameYear(as date: Date) -> Bool { isEqual(to: date, toGranularity: .year) }
func isInSameMonth(as date: Date) -> Bool { isEqual(to: date, toGranularity: .month) }
func isInSameWeek(as date: Date) -> Bool { isEqual(to: date, toGranularity: .weekOfYear) }
func isInSameDay(as date: Date) -> Bool { Calendar.current.isDate(self, inSameDayAs: date) }
var isInThisYear: Bool { isInSameYear(as: Date()) }
var isInThisMonth: Bool { isInSameMonth(as: Date()) }
var isInThisWeek: Bool { isInSameWeek(as: Date()) }
var isInYesterday: Bool { Calendar.current.isDateInYesterday(self) }
var isInToday: Bool { Calendar.current.isDateInToday(self) }
var isInTomorrow: Bool { Calendar.current.isDateInTomorrow(self) }
var isInTheFuture: Bool { self > Date() }
var isInThePast: Bool { self < 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.
iOS detect if date is within last week
-(BOOL) dayOccuredDuringLast7Days
{
NSDate *now = [NSDate date]; // now
NSDate *today;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit // beginning of this day
startDate:&today // save it here
interval:NULL
forDate:now];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.day = -7; // lets go 7 days back from today
NSDate * oneWeekBefore = [[NSCalendar currentCalendar] dateByAddingComponents:comp
toDate:today
options:0];
if ([self compare: oneWeekBefore] == NSOrderedDescending) {
if ( [self compare:today] == NSOrderedAscending ) { // or now?
return YES;
}
}
return NO;
}
a complete command line example for last 7 days and yesterday. as category on NSDate
#import <Foundation/Foundation.h>
@interface NSDate (ExtendedComparions)
-(BOOL) dayOccuredDuringLast7Days;
-(BOOL) dayWasYesterday;
@end
@implementation NSDate (ExtendedComparions)
-(BOOL) _occuredDaysBeforeToday:(NSUInteger) nDaysBefore
{
NSDate *now = [NSDate date]; // now
NSDate *today;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit // beginning of this day
startDate:&today // save it here
interval:NULL
forDate:now];
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.day = -nDaysBefore; // lets go N days back from today
NSDate * before = [[NSCalendar currentCalendar] dateByAddingComponents:comp
toDate:today
options:0];
if ([self compare: before] == NSOrderedDescending) {
if ( [self compare:today] == NSOrderedAscending ) {
return YES;
}
}
return NO;
}
-(BOOL) dayOccuredDuringLast7Days
{
return [self _occuredDaysBeforeToday:7];
}
-(BOOL) dayWasYesterday
{
return [self _occuredDaysBeforeToday:1];
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSDate *now =[NSDate date];
NSDate *twoDaysBefore = [[NSCalendar currentCalendar] dateByAddingComponents:(
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = -2;
comps;
})
toDate:now
options:0];
if ([twoDaysBefore dayOccuredDuringLast7Days]) {
NSLog(@"last week");
} else {
NSLog(@"not last week");
}
if ([twoDaysBefore dayWasYesterday]) {
NSLog(@"yesteday");
} else {
NSLog(@"not yesterday");
}
}
return 0;
}
iOS Swift - Best way to compare if a NSDate is between now and x days away
If you know how to compare two dates you can use dateByAddingUnit to find out the date xDays from today as follow:
edit/update: Swift 3.x - Swift 4
extension Date {
func adding(days: Int) -> Date {
return Calendar.current.date(byAdding: .day, value: days, to: self)!
}
}
let fiveDaysFromToday = Date().adding(days: 5) // "Jun 19, 2017 at 5:25 PM"
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)
Related Topics
How to Get the Font Name from an Otf or Ttf File
Choosing the Right iOS Xml Parser
iOS Nsdate() Returns Incorrect Time
App Killed by Sigkill When Changing Privacy Settings
iOS Simulator Games Run Very Slow (Low Fps)
Creating Delegates on the Spot with Blocks
How to Prevent Uinavigationbar from Covering Top of View in iOS 7
Sharing Data Between an iOS 8 Share Extension and Main App
Load Local HTML into Uiwebview Using Swift
How to Keep Uitableview Contentoffset After Calling -Reloaddata
Save Images with Phimagemanager to Custom Album
How to Password Protect Writing to Nfc Ntag216 Tag on iOS 13 Using Nfc Core
Uitableview Checkmark Only One Row at a Time
Using Scrollview Programmatically in Swift 3