Swift days between two NSDates
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?
E.g. like in Ruby I would do:
(end_date - start_date).to_i
ios swift date date-difference
add a comment |
I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?
E.g. like in Ruby I would do:
(end_date - start_date).to_i
ios swift date date-difference
4
I think you still have to use NSCalendar and NSDateComponents (for which there must be hundreds of answers on SO). - If you are looking for something "new and awesome possibility" then it would be helpful to show your present solution for comparison.
– Martin R
Jul 13 '14 at 14:15
1
This is now very easy, and you don't have to use "NS" anything. I typed in an answer for 2017, to copy and paste.
– Fattie
Jul 20 '17 at 23:00
add a comment |
I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?
E.g. like in Ruby I would do:
(end_date - start_date).to_i
ios swift date date-difference
I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?
E.g. like in Ruby I would do:
(end_date - start_date).to_i
ios swift date date-difference
ios swift date date-difference
edited Apr 16 '18 at 9:45
Krunal
42.1k21161175
42.1k21161175
asked Jul 13 '14 at 13:58
NikoNiko
1,80743560
1,80743560
4
I think you still have to use NSCalendar and NSDateComponents (for which there must be hundreds of answers on SO). - If you are looking for something "new and awesome possibility" then it would be helpful to show your present solution for comparison.
– Martin R
Jul 13 '14 at 14:15
1
This is now very easy, and you don't have to use "NS" anything. I typed in an answer for 2017, to copy and paste.
– Fattie
Jul 20 '17 at 23:00
add a comment |
4
I think you still have to use NSCalendar and NSDateComponents (for which there must be hundreds of answers on SO). - If you are looking for something "new and awesome possibility" then it would be helpful to show your present solution for comparison.
– Martin R
Jul 13 '14 at 14:15
1
This is now very easy, and you don't have to use "NS" anything. I typed in an answer for 2017, to copy and paste.
– Fattie
Jul 20 '17 at 23:00
4
4
I think you still have to use NSCalendar and NSDateComponents (for which there must be hundreds of answers on SO). - If you are looking for something "new and awesome possibility" then it would be helpful to show your present solution for comparison.
– Martin R
Jul 13 '14 at 14:15
I think you still have to use NSCalendar and NSDateComponents (for which there must be hundreds of answers on SO). - If you are looking for something "new and awesome possibility" then it would be helpful to show your present solution for comparison.
– Martin R
Jul 13 '14 at 14:15
1
1
This is now very easy, and you don't have to use "NS" anything. I typed in an answer for 2017, to copy and paste.
– Fattie
Jul 20 '17 at 23:00
This is now very easy, and you don't have to use "NS" anything. I typed in an answer for 2017, to copy and paste.
– Fattie
Jul 20 '17 at 23:00
add a comment |
23 Answers
23
active
oldest
votes
The accepted answer won't return the correct day number between two dates. You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00
and 2015-01-02 09:00
, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).
If your purpose is to get the exact day number between two dates, you can work around this issue like this:
// Assuming that firstDate and secondDate are defined
// ...
let calendar = NSCalendar.currentCalendar()
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)
let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: )
components.day // This will return the number of day(s) between dates
Swift 3 and Swift 4 Version
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)
let components = calendar.dateComponents([.day], from: date1, to: date2)
10
You may actually want to check for 12pm (noon) instead of startOfDayForDate -- should be less likely to bork due to adjusting timezones and DST.
– brandonscript
Feb 15 '16 at 20:50
6
Setting the dates to noon can be done like this:calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: firstDate))
– MonsieurDart
May 15 '17 at 22:08
Swift3 version in giving erroe in xcode 9.3
– AsimRazaKhan
May 9 '18 at 11:15
I needed this, and I searched for your name in stackoverflow. thanks again
– osrl
Apr 3 at 17:19
add a comment |
Here is my answer for Swift 2:
func daysBetweenDates(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: )
return components.day
}
4
That looks a lot shorter and easier than the examples before.
– Niko
Aug 26 '15 at 6:41
I successfully used this with components of @vikingosegundo post above. It returns an integer representing the correct number of days between two dates. <thumbs up>
– Delete My Account
May 13 '16 at 12:43
I like it but the function name should be "daysBetweenDates"
– mbonness
Jun 6 '16 at 3:28
@mbonness yes you are right.
– iphaaw
Jun 6 '16 at 11:11
2
This returns 0 if we are comparingtoday
andtomorrow
– tawheed
Oct 15 '17 at 13:44
add a comment |
I see a couple Swift3 answers so I'll add my own:
public static func daysBetween(start: Date, end: Date) -> Int {
return Calendar.current.dateComponents([.day], from: start, to: end).day!
}
The naming feels more Swifty, it's one line, and using the latest dateComponents()
method.
add a comment |
I translated my Objective-C answer
let start = "2010-09-01"
let end = "2010-09-05"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let startDate:NSDate = dateFormatter.dateFromString(start)
let endDate:NSDate = dateFormatter.dateFromString(end)
let cal = NSCalendar.currentCalendar()
let unit:NSCalendarUnit = .Day
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)
println(components)
result
<NSDateComponents: 0x10280a8a0>
Day: 4
The hardest part was that the autocompletion insists fromDate and toDate would be NSDate?
, but indeed they must be NSDate!
as shown in the reference.
I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.
Looks like.DayCalendarUnit
is deprecated. I believe now you should use.CalendarUnitDay
instead.
– TaylorAllred
Apr 23 '15 at 20:08
2
options is now an expected parameter
– Departamento B
Nov 6 '15 at 21:57
2
Running Swift 2 this works for me:let components = cal.components(.Day, fromDate: startDate, toDate: endDate, options: )
– Andrej
Mar 10 '16 at 10:07
@TaylorAllred just.Day
now
– William GP
May 19 '16 at 3:54
add a comment |
Here is very nice, Date
extension to get difference between dates in years, months, days, hours, minutes, seconds
extension Date {
func years(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.year], from: sinceDate, to: self).year
}
func months(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.month], from: sinceDate, to: self).month
}
func days(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.day], from: sinceDate, to: self).day
}
func hours(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.hour], from: sinceDate, to: self).hour
}
func minutes(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.minute], from: sinceDate, to: self).minute
}
func seconds(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.second], from: sinceDate, to: self).second
}
}
date
should besinceDate
in function parameters.
– TheTiger
Mar 28 '18 at 6:14
@TheTiger - Thank you very much for highlighting the biggest mistake of this answer.. I'll practically test and update answer soon.
– Krunal
Mar 28 '18 at 7:14
1
My pleasure! I have tested it fordays
and it works fine.
– TheTiger
Mar 28 '18 at 7:15
1
Good answer. I’d only suggestfunc years(since date: Date) -> Int? { return Calendar.current.dateComponents[.year], from: date, to: self).years }
, and you could the call it aslet y = date1.years(since: date2)
. That might be more consistent with modern naming conventions.
– Rob
Feb 24 at 7:34
add a comment |
Update for Swift 3 iOS 10 Beta 4
func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
return components.day!
}
add a comment |
Here is the answer for Swift 3 (tested for IOS 10 Beta)
func daysBetweenDates(startDate: Date, endDate: Date) -> Int
{
let calendar = Calendar.current
let components = calendar.components([.day], from: startDate, to: endDate, options: )
return components.day!
}
Then you can call it like this
let pickedDate: Date = sender.date
let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
print("Num of Days: (NumOfDays)")
add a comment |
Swift 3. Thanks to Emin Buğra Saral above for the startOfDay
suggestion.
extension Date {
func daysBetween(date: Date) -> Int {
return Date.daysBetween(start: self, end: date)
}
static func daysBetween(start: Date, end: Date) -> Int {
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: start)
let date2 = calendar.startOfDay(for: end)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
}
Usage:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let start = dateFormatter.date(from: "2017-01-01")!
let end = dateFormatter.date(from: "2018-01-01")!
let diff = Date.daysBetween(start: start, end: end) // 365
1
it would definitely be better to move them both to noon, rather than 00:00 to avoid many problems.
– Fattie
Feb 21 '17 at 15:23
add a comment |
The things built into swift are still very basic. As they should be at this early stage. But you can add your own stuff with the risk that comes with overloading operators and global domain functions. They will be local to your module though.
let now = NSDate()
let seventies = NSDate(timeIntervalSince1970: 0)
// Standard solution still works
let days = NSCalendar.currentCalendar().components(.CalendarUnitDay,
fromDate: seventies, toDate: now, options: nil).day
// Flashy swift... maybe...
func -(lhs:NSDate, rhs:NSDate) -> DateRange {
return DateRange(startDate: rhs, endDate: lhs)
}
class DateRange {
let startDate:NSDate
let endDate:NSDate
var calendar = NSCalendar.currentCalendar()
var days: Int {
return calendar.components(.CalendarUnitDay,
fromDate: startDate, toDate: endDate, options: nil).day
}
var months: Int {
return calendar.components(.CalendarUnitMonth,
fromDate: startDate, toDate: endDate, options: nil).month
}
init(startDate:NSDate, endDate:NSDate) {
self.startDate = startDate
self.endDate = endDate
}
}
// Now you can do this...
(now - seventies).months
(now - seventies).days
17
Don't use (24*60*60) for the length of a day. This does not take daylight saving time transitions into account.
– Martin R
Jul 13 '14 at 16:35
I think NSDate would adjust for that since it always uses GMT and daylight saving is just a formatting or localisation upon that. For sure it gets trickier for months, years or anything of really variable length though.
– Daniel Schlaug
Jul 13 '14 at 16:42
1
@MartinR I had to try it to believe it but indeed, now that I did I also saw that wikipedia mentions this. You are correct. Thanks for being stubborn with me.
– Daniel Schlaug
Jul 13 '14 at 22:01
1
There, edited to be correct. But the flashiness kind of went away.
– Daniel Schlaug
Jul 13 '14 at 22:17
1
it is defined by location, point of time and calendar system. the hebrew calendar has a leap month. there is a great wwdc video: performing calendar calculation — a must-see for every cocoa coder.
– vikingosegundo
Jul 14 '14 at 16:17
|
show 6 more comments
Here is my answer for Swift 3:
func daysBetweenDates(startDate: NSDate, endDate: NSDate, inTimeZone timeZone: TimeZone? = nil) -> Int {
var calendar = Calendar.current
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
let dateComponents = calendar.dateComponents([.day], from: startDate.startOfDay, to: endDate.startOfDay)
return dateComponents.day!
}
add a comment |
There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.
It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.
add a comment |
I'm going to add my version even though this thread is a year old. My code looks like this:
var name = txtName.stringValue // Get the users name
// Get the date components from the window controls
var dateComponents = NSDateComponents()
dateComponents.day = txtDOBDay.integerValue
dateComponents.month = txtDOBMonth.integerValue
dateComponents.year = txtDOBYear.integerValue
// Make a Gregorian calendar
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
// Get the two dates we need
var birthdate = calendar?.dateFromComponents(dateComponents)
let currentDate = NSDate()
var durationDateComponents = calendar?.components(NSCalendarUnit.CalendarUnitDay, fromDate: birthdate!, toDate: currentDate, options: nil)
let numberOfDaysAlive = durationDateComponents?.day
println("(numberOfDaysAlive!)")
txtGreeting.stringValue = "Hello (name), You have been alive for (numberOfDaysAlive!) days."
I hope it helps someone.
Cheers,
add a comment |
Erin's method updated to Swift 3, This shows days from today (disregarding time of day)
func daysBetweenDates( endDate: Date) -> Int
let calendar: Calendar = Calendar.current
let date1 = calendar.startOfDay(for: Date())
let date2 = calendar.startOfDay(for: secondDate)
return calendar.dateComponents([.day], from: date1, to: date2).day!
}
add a comment |
Swift 3.2
extension DateComponentsFormatter {
func difference(from fromDate: Date, to toDate: Date) -> String? {
self.allowedUnits = [.year,.month,.weekOfMonth,.day]
self.maximumUnitCount = 1
self.unitsStyle = .full
return self.string(from: fromDate, to: toDate)
}
}
add a comment |
All answer is good. But for Localizations we need calculates a number of decimal days in between two dates. so we can provide the sustainable decimal format.
// This method returns the fractional number of days between to dates
func getFractionalDaysBetweenDates(date1: Date, date2: Date) -> Double {
let components = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)
var decimalDays = Double(components.day!)
decimalDays += Double(components.hour!) / 24.0
return decimalDays
}
add a comment |
Swift 3 - Days from today until date
func daysUntilDate(endDateComponents: DateComponents) -> Int
{
let cal = Calendar.current
var components = cal.dateComponents([.era, .year, .month, .day], from: NSDate() as Date)
let today = cal.date(from: components)
let otherDate = cal.date(from: endDateComponents)
components = cal.dateComponents([Calendar.Component.day], from: (today! as Date), to: otherDate!)
return components.day!
}
Call function like this
// Days from today until date
var examnDate = DateComponents()
examnDate.year = 2016
examnDate.month = 12
examnDate.day = 15
let daysCount = daysUntilDate(endDateComponents: examnDate)
add a comment |
easier option would be to create a extension on Date
public extension Date {
public var currentCalendar: Calendar {
return Calendar.autoupdatingCurrent
}
public func daysBetween(_ date: Date) -> Int {
let components = currentCalendar.dateComponents([.day], from: self, to: date)
return components.day!
}
}
add a comment |
func completeOffset(from date:Date) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief
return formatter.string(from: Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date, to: self))
}
if you need year month days and hours as string use this
var tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
let dc = tomorrow.completeOffset(from: Date())
add a comment |
Nice handy one liner :
extension Date {
var daysFromNow: Int {
return Calendar.current.dateComponents([.day], from: Date(), to: self).day!
}
}
add a comment |
This returns an absolute difference in days between some Date
and today:
extension Date {
func daysFromToday() -> Int {
return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)
}
}
and then use it:
if someDate.daysFromToday() >= 7 {
// at least a week from today
}
add a comment |
Swift 4
func getDateHeader(indexPath: Int) -> String {
let formatter2 = DateFormatter()
formatter2.dateFormat = "MM-dd-yyyy"
var dateDeadline : Date?
dateDeadline = formatter2.date(from: arrCompletedDate[indexPath] as! String)
let currentTime = dateDeadline?.unixTimestamp
let calendar = NSCalendar.current
let date = NSDate(timeIntervalSince1970: Double(currentTime!))
if calendar.isDateInYesterday(date as Date) { return "Yesterday" }
else if calendar.isDateInToday(date as Date) { return "Today" }
else if calendar.isDateInTomorrow(date as Date) { return "Tomorrow" }
else {
let startOfNow = calendar.startOfDay(for: NSDate() as Date)
let startOfTimeStamp = calendar.startOfDay(for: date as Date)
let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
let day = components.day!
if day < 1 { return "(abs(day)) days ago" }
else { return "In (day) days" }
}
}
add a comment |
let calendar = NSCalendar.currentCalendar();
let component1 = calendar.component(.Day, fromDate: fromDate)
let component2 = calendar.component(.Day, fromDate: toDate)
let difference = component1 - component2
1
that measures the difference between the number portion of the dates- I.e. 21st January to 22nd of February will give 1 day, not 32 days as it should
– Peter Johnson
Aug 28 '16 at 14:16
add a comment |
2017 version, copy and paste
func simpleIndex(ofDate: Date) -> Int {
// index here just means today 0, yesterday -1, tomorrow 1 etc.
let c = Calendar.current
let todayRightNow = Date()
let d = c.date(bySetting: .hour, value: 13, of: ofDate)
let t = c.date(bySetting: .hour, value: 13, of: todayRightNow)
if d == nil || today == nil {
print("weird problem simpleIndex#ofDate")
return 0
}
let r = c.dateComponents([.day], from: today!, to: d!)
// yesterday is negative one, tomorrow is one
if let o = r.value(for: .day) {
return o
}
else {
print("another weird problem simpleIndex#ofDate")
return 0
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24723431%2fswift-days-between-two-nsdates%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
23 Answers
23
active
oldest
votes
23 Answers
23
active
oldest
votes
active
oldest
votes
active
oldest
votes
The accepted answer won't return the correct day number between two dates. You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00
and 2015-01-02 09:00
, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).
If your purpose is to get the exact day number between two dates, you can work around this issue like this:
// Assuming that firstDate and secondDate are defined
// ...
let calendar = NSCalendar.currentCalendar()
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)
let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: )
components.day // This will return the number of day(s) between dates
Swift 3 and Swift 4 Version
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)
let components = calendar.dateComponents([.day], from: date1, to: date2)
10
You may actually want to check for 12pm (noon) instead of startOfDayForDate -- should be less likely to bork due to adjusting timezones and DST.
– brandonscript
Feb 15 '16 at 20:50
6
Setting the dates to noon can be done like this:calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: firstDate))
– MonsieurDart
May 15 '17 at 22:08
Swift3 version in giving erroe in xcode 9.3
– AsimRazaKhan
May 9 '18 at 11:15
I needed this, and I searched for your name in stackoverflow. thanks again
– osrl
Apr 3 at 17:19
add a comment |
The accepted answer won't return the correct day number between two dates. You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00
and 2015-01-02 09:00
, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).
If your purpose is to get the exact day number between two dates, you can work around this issue like this:
// Assuming that firstDate and secondDate are defined
// ...
let calendar = NSCalendar.currentCalendar()
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)
let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: )
components.day // This will return the number of day(s) between dates
Swift 3 and Swift 4 Version
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)
let components = calendar.dateComponents([.day], from: date1, to: date2)
10
You may actually want to check for 12pm (noon) instead of startOfDayForDate -- should be less likely to bork due to adjusting timezones and DST.
– brandonscript
Feb 15 '16 at 20:50
6
Setting the dates to noon can be done like this:calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: firstDate))
– MonsieurDart
May 15 '17 at 22:08
Swift3 version in giving erroe in xcode 9.3
– AsimRazaKhan
May 9 '18 at 11:15
I needed this, and I searched for your name in stackoverflow. thanks again
– osrl
Apr 3 at 17:19
add a comment |
The accepted answer won't return the correct day number between two dates. You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00
and 2015-01-02 09:00
, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).
If your purpose is to get the exact day number between two dates, you can work around this issue like this:
// Assuming that firstDate and secondDate are defined
// ...
let calendar = NSCalendar.currentCalendar()
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)
let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: )
components.day // This will return the number of day(s) between dates
Swift 3 and Swift 4 Version
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)
let components = calendar.dateComponents([.day], from: date1, to: date2)
The accepted answer won't return the correct day number between two dates. You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00
and 2015-01-02 09:00
, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).
If your purpose is to get the exact day number between two dates, you can work around this issue like this:
// Assuming that firstDate and secondDate are defined
// ...
let calendar = NSCalendar.currentCalendar()
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)
let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: )
components.day // This will return the number of day(s) between dates
Swift 3 and Swift 4 Version
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)
let components = calendar.dateComponents([.day], from: date1, to: date2)
edited Nov 16 '18 at 17:32
Damon
5361619
5361619
answered Jan 27 '15 at 5:03
Emin Buğra SaralEmin Buğra Saral
2,45411219
2,45411219
10
You may actually want to check for 12pm (noon) instead of startOfDayForDate -- should be less likely to bork due to adjusting timezones and DST.
– brandonscript
Feb 15 '16 at 20:50
6
Setting the dates to noon can be done like this:calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: firstDate))
– MonsieurDart
May 15 '17 at 22:08
Swift3 version in giving erroe in xcode 9.3
– AsimRazaKhan
May 9 '18 at 11:15
I needed this, and I searched for your name in stackoverflow. thanks again
– osrl
Apr 3 at 17:19
add a comment |
10
You may actually want to check for 12pm (noon) instead of startOfDayForDate -- should be less likely to bork due to adjusting timezones and DST.
– brandonscript
Feb 15 '16 at 20:50
6
Setting the dates to noon can be done like this:calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: firstDate))
– MonsieurDart
May 15 '17 at 22:08
Swift3 version in giving erroe in xcode 9.3
– AsimRazaKhan
May 9 '18 at 11:15
I needed this, and I searched for your name in stackoverflow. thanks again
– osrl
Apr 3 at 17:19
10
10
You may actually want to check for 12pm (noon) instead of startOfDayForDate -- should be less likely to bork due to adjusting timezones and DST.
– brandonscript
Feb 15 '16 at 20:50
You may actually want to check for 12pm (noon) instead of startOfDayForDate -- should be less likely to bork due to adjusting timezones and DST.
– brandonscript
Feb 15 '16 at 20:50
6
6
Setting the dates to noon can be done like this:
calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: firstDate))
– MonsieurDart
May 15 '17 at 22:08
Setting the dates to noon can be done like this:
calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: firstDate))
– MonsieurDart
May 15 '17 at 22:08
Swift3 version in giving erroe in xcode 9.3
– AsimRazaKhan
May 9 '18 at 11:15
Swift3 version in giving erroe in xcode 9.3
– AsimRazaKhan
May 9 '18 at 11:15
I needed this, and I searched for your name in stackoverflow. thanks again
– osrl
Apr 3 at 17:19
I needed this, and I searched for your name in stackoverflow. thanks again
– osrl
Apr 3 at 17:19
add a comment |
Here is my answer for Swift 2:
func daysBetweenDates(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: )
return components.day
}
4
That looks a lot shorter and easier than the examples before.
– Niko
Aug 26 '15 at 6:41
I successfully used this with components of @vikingosegundo post above. It returns an integer representing the correct number of days between two dates. <thumbs up>
– Delete My Account
May 13 '16 at 12:43
I like it but the function name should be "daysBetweenDates"
– mbonness
Jun 6 '16 at 3:28
@mbonness yes you are right.
– iphaaw
Jun 6 '16 at 11:11
2
This returns 0 if we are comparingtoday
andtomorrow
– tawheed
Oct 15 '17 at 13:44
add a comment |
Here is my answer for Swift 2:
func daysBetweenDates(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: )
return components.day
}
4
That looks a lot shorter and easier than the examples before.
– Niko
Aug 26 '15 at 6:41
I successfully used this with components of @vikingosegundo post above. It returns an integer representing the correct number of days between two dates. <thumbs up>
– Delete My Account
May 13 '16 at 12:43
I like it but the function name should be "daysBetweenDates"
– mbonness
Jun 6 '16 at 3:28
@mbonness yes you are right.
– iphaaw
Jun 6 '16 at 11:11
2
This returns 0 if we are comparingtoday
andtomorrow
– tawheed
Oct 15 '17 at 13:44
add a comment |
Here is my answer for Swift 2:
func daysBetweenDates(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: )
return components.day
}
Here is my answer for Swift 2:
func daysBetweenDates(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: )
return components.day
}
edited Jun 6 '16 at 11:10
answered Aug 23 '15 at 9:33
iphaawiphaaw
2,98153554
2,98153554
4
That looks a lot shorter and easier than the examples before.
– Niko
Aug 26 '15 at 6:41
I successfully used this with components of @vikingosegundo post above. It returns an integer representing the correct number of days between two dates. <thumbs up>
– Delete My Account
May 13 '16 at 12:43
I like it but the function name should be "daysBetweenDates"
– mbonness
Jun 6 '16 at 3:28
@mbonness yes you are right.
– iphaaw
Jun 6 '16 at 11:11
2
This returns 0 if we are comparingtoday
andtomorrow
– tawheed
Oct 15 '17 at 13:44
add a comment |
4
That looks a lot shorter and easier than the examples before.
– Niko
Aug 26 '15 at 6:41
I successfully used this with components of @vikingosegundo post above. It returns an integer representing the correct number of days between two dates. <thumbs up>
– Delete My Account
May 13 '16 at 12:43
I like it but the function name should be "daysBetweenDates"
– mbonness
Jun 6 '16 at 3:28
@mbonness yes you are right.
– iphaaw
Jun 6 '16 at 11:11
2
This returns 0 if we are comparingtoday
andtomorrow
– tawheed
Oct 15 '17 at 13:44
4
4
That looks a lot shorter and easier than the examples before.
– Niko
Aug 26 '15 at 6:41
That looks a lot shorter and easier than the examples before.
– Niko
Aug 26 '15 at 6:41
I successfully used this with components of @vikingosegundo post above. It returns an integer representing the correct number of days between two dates. <thumbs up>
– Delete My Account
May 13 '16 at 12:43
I successfully used this with components of @vikingosegundo post above. It returns an integer representing the correct number of days between two dates. <thumbs up>
– Delete My Account
May 13 '16 at 12:43
I like it but the function name should be "daysBetweenDates"
– mbonness
Jun 6 '16 at 3:28
I like it but the function name should be "daysBetweenDates"
– mbonness
Jun 6 '16 at 3:28
@mbonness yes you are right.
– iphaaw
Jun 6 '16 at 11:11
@mbonness yes you are right.
– iphaaw
Jun 6 '16 at 11:11
2
2
This returns 0 if we are comparing
today
and tomorrow
– tawheed
Oct 15 '17 at 13:44
This returns 0 if we are comparing
today
and tomorrow
– tawheed
Oct 15 '17 at 13:44
add a comment |
I see a couple Swift3 answers so I'll add my own:
public static func daysBetween(start: Date, end: Date) -> Int {
return Calendar.current.dateComponents([.day], from: start, to: end).day!
}
The naming feels more Swifty, it's one line, and using the latest dateComponents()
method.
add a comment |
I see a couple Swift3 answers so I'll add my own:
public static func daysBetween(start: Date, end: Date) -> Int {
return Calendar.current.dateComponents([.day], from: start, to: end).day!
}
The naming feels more Swifty, it's one line, and using the latest dateComponents()
method.
add a comment |
I see a couple Swift3 answers so I'll add my own:
public static func daysBetween(start: Date, end: Date) -> Int {
return Calendar.current.dateComponents([.day], from: start, to: end).day!
}
The naming feels more Swifty, it's one line, and using the latest dateComponents()
method.
I see a couple Swift3 answers so I'll add my own:
public static func daysBetween(start: Date, end: Date) -> Int {
return Calendar.current.dateComponents([.day], from: start, to: end).day!
}
The naming feels more Swifty, it's one line, and using the latest dateComponents()
method.
answered Aug 16 '16 at 19:40
trevor-etrevor-e
7,37084166
7,37084166
add a comment |
add a comment |
I translated my Objective-C answer
let start = "2010-09-01"
let end = "2010-09-05"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let startDate:NSDate = dateFormatter.dateFromString(start)
let endDate:NSDate = dateFormatter.dateFromString(end)
let cal = NSCalendar.currentCalendar()
let unit:NSCalendarUnit = .Day
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)
println(components)
result
<NSDateComponents: 0x10280a8a0>
Day: 4
The hardest part was that the autocompletion insists fromDate and toDate would be NSDate?
, but indeed they must be NSDate!
as shown in the reference.
I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.
Looks like.DayCalendarUnit
is deprecated. I believe now you should use.CalendarUnitDay
instead.
– TaylorAllred
Apr 23 '15 at 20:08
2
options is now an expected parameter
– Departamento B
Nov 6 '15 at 21:57
2
Running Swift 2 this works for me:let components = cal.components(.Day, fromDate: startDate, toDate: endDate, options: )
– Andrej
Mar 10 '16 at 10:07
@TaylorAllred just.Day
now
– William GP
May 19 '16 at 3:54
add a comment |
I translated my Objective-C answer
let start = "2010-09-01"
let end = "2010-09-05"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let startDate:NSDate = dateFormatter.dateFromString(start)
let endDate:NSDate = dateFormatter.dateFromString(end)
let cal = NSCalendar.currentCalendar()
let unit:NSCalendarUnit = .Day
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)
println(components)
result
<NSDateComponents: 0x10280a8a0>
Day: 4
The hardest part was that the autocompletion insists fromDate and toDate would be NSDate?
, but indeed they must be NSDate!
as shown in the reference.
I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.
Looks like.DayCalendarUnit
is deprecated. I believe now you should use.CalendarUnitDay
instead.
– TaylorAllred
Apr 23 '15 at 20:08
2
options is now an expected parameter
– Departamento B
Nov 6 '15 at 21:57
2
Running Swift 2 this works for me:let components = cal.components(.Day, fromDate: startDate, toDate: endDate, options: )
– Andrej
Mar 10 '16 at 10:07
@TaylorAllred just.Day
now
– William GP
May 19 '16 at 3:54
add a comment |
I translated my Objective-C answer
let start = "2010-09-01"
let end = "2010-09-05"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let startDate:NSDate = dateFormatter.dateFromString(start)
let endDate:NSDate = dateFormatter.dateFromString(end)
let cal = NSCalendar.currentCalendar()
let unit:NSCalendarUnit = .Day
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)
println(components)
result
<NSDateComponents: 0x10280a8a0>
Day: 4
The hardest part was that the autocompletion insists fromDate and toDate would be NSDate?
, but indeed they must be NSDate!
as shown in the reference.
I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.
I translated my Objective-C answer
let start = "2010-09-01"
let end = "2010-09-05"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let startDate:NSDate = dateFormatter.dateFromString(start)
let endDate:NSDate = dateFormatter.dateFromString(end)
let cal = NSCalendar.currentCalendar()
let unit:NSCalendarUnit = .Day
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)
println(components)
result
<NSDateComponents: 0x10280a8a0>
Day: 4
The hardest part was that the autocompletion insists fromDate and toDate would be NSDate?
, but indeed they must be NSDate!
as shown in the reference.
I don't see how a good solution with an operator would look like, as you want to specify the unit differently in each case. You could return the time interval, but than won't you gain much.
edited May 23 '17 at 12:26
Community♦
11
11
answered Jul 13 '14 at 17:37
vikingosegundovikingosegundo
48.8k14117163
48.8k14117163
Looks like.DayCalendarUnit
is deprecated. I believe now you should use.CalendarUnitDay
instead.
– TaylorAllred
Apr 23 '15 at 20:08
2
options is now an expected parameter
– Departamento B
Nov 6 '15 at 21:57
2
Running Swift 2 this works for me:let components = cal.components(.Day, fromDate: startDate, toDate: endDate, options: )
– Andrej
Mar 10 '16 at 10:07
@TaylorAllred just.Day
now
– William GP
May 19 '16 at 3:54
add a comment |
Looks like.DayCalendarUnit
is deprecated. I believe now you should use.CalendarUnitDay
instead.
– TaylorAllred
Apr 23 '15 at 20:08
2
options is now an expected parameter
– Departamento B
Nov 6 '15 at 21:57
2
Running Swift 2 this works for me:let components = cal.components(.Day, fromDate: startDate, toDate: endDate, options: )
– Andrej
Mar 10 '16 at 10:07
@TaylorAllred just.Day
now
– William GP
May 19 '16 at 3:54
Looks like
.DayCalendarUnit
is deprecated. I believe now you should use .CalendarUnitDay
instead.– TaylorAllred
Apr 23 '15 at 20:08
Looks like
.DayCalendarUnit
is deprecated. I believe now you should use .CalendarUnitDay
instead.– TaylorAllred
Apr 23 '15 at 20:08
2
2
options is now an expected parameter
– Departamento B
Nov 6 '15 at 21:57
options is now an expected parameter
– Departamento B
Nov 6 '15 at 21:57
2
2
Running Swift 2 this works for me:
let components = cal.components(.Day, fromDate: startDate, toDate: endDate, options: )
– Andrej
Mar 10 '16 at 10:07
Running Swift 2 this works for me:
let components = cal.components(.Day, fromDate: startDate, toDate: endDate, options: )
– Andrej
Mar 10 '16 at 10:07
@TaylorAllred just
.Day
now– William GP
May 19 '16 at 3:54
@TaylorAllred just
.Day
now– William GP
May 19 '16 at 3:54
add a comment |
Here is very nice, Date
extension to get difference between dates in years, months, days, hours, minutes, seconds
extension Date {
func years(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.year], from: sinceDate, to: self).year
}
func months(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.month], from: sinceDate, to: self).month
}
func days(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.day], from: sinceDate, to: self).day
}
func hours(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.hour], from: sinceDate, to: self).hour
}
func minutes(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.minute], from: sinceDate, to: self).minute
}
func seconds(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.second], from: sinceDate, to: self).second
}
}
date
should besinceDate
in function parameters.
– TheTiger
Mar 28 '18 at 6:14
@TheTiger - Thank you very much for highlighting the biggest mistake of this answer.. I'll practically test and update answer soon.
– Krunal
Mar 28 '18 at 7:14
1
My pleasure! I have tested it fordays
and it works fine.
– TheTiger
Mar 28 '18 at 7:15
1
Good answer. I’d only suggestfunc years(since date: Date) -> Int? { return Calendar.current.dateComponents[.year], from: date, to: self).years }
, and you could the call it aslet y = date1.years(since: date2)
. That might be more consistent with modern naming conventions.
– Rob
Feb 24 at 7:34
add a comment |
Here is very nice, Date
extension to get difference between dates in years, months, days, hours, minutes, seconds
extension Date {
func years(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.year], from: sinceDate, to: self).year
}
func months(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.month], from: sinceDate, to: self).month
}
func days(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.day], from: sinceDate, to: self).day
}
func hours(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.hour], from: sinceDate, to: self).hour
}
func minutes(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.minute], from: sinceDate, to: self).minute
}
func seconds(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.second], from: sinceDate, to: self).second
}
}
date
should besinceDate
in function parameters.
– TheTiger
Mar 28 '18 at 6:14
@TheTiger - Thank you very much for highlighting the biggest mistake of this answer.. I'll practically test and update answer soon.
– Krunal
Mar 28 '18 at 7:14
1
My pleasure! I have tested it fordays
and it works fine.
– TheTiger
Mar 28 '18 at 7:15
1
Good answer. I’d only suggestfunc years(since date: Date) -> Int? { return Calendar.current.dateComponents[.year], from: date, to: self).years }
, and you could the call it aslet y = date1.years(since: date2)
. That might be more consistent with modern naming conventions.
– Rob
Feb 24 at 7:34
add a comment |
Here is very nice, Date
extension to get difference between dates in years, months, days, hours, minutes, seconds
extension Date {
func years(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.year], from: sinceDate, to: self).year
}
func months(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.month], from: sinceDate, to: self).month
}
func days(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.day], from: sinceDate, to: self).day
}
func hours(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.hour], from: sinceDate, to: self).hour
}
func minutes(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.minute], from: sinceDate, to: self).minute
}
func seconds(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.second], from: sinceDate, to: self).second
}
}
Here is very nice, Date
extension to get difference between dates in years, months, days, hours, minutes, seconds
extension Date {
func years(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.year], from: sinceDate, to: self).year
}
func months(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.month], from: sinceDate, to: self).month
}
func days(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.day], from: sinceDate, to: self).day
}
func hours(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.hour], from: sinceDate, to: self).hour
}
func minutes(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.minute], from: sinceDate, to: self).minute
}
func seconds(sinceDate: Date) -> Int? {
return Calendar.current.dateComponents([.second], from: sinceDate, to: self).second
}
}
edited Apr 16 '18 at 9:41
answered Aug 18 '17 at 13:30
KrunalKrunal
42.1k21161175
42.1k21161175
date
should besinceDate
in function parameters.
– TheTiger
Mar 28 '18 at 6:14
@TheTiger - Thank you very much for highlighting the biggest mistake of this answer.. I'll practically test and update answer soon.
– Krunal
Mar 28 '18 at 7:14
1
My pleasure! I have tested it fordays
and it works fine.
– TheTiger
Mar 28 '18 at 7:15
1
Good answer. I’d only suggestfunc years(since date: Date) -> Int? { return Calendar.current.dateComponents[.year], from: date, to: self).years }
, and you could the call it aslet y = date1.years(since: date2)
. That might be more consistent with modern naming conventions.
– Rob
Feb 24 at 7:34
add a comment |
date
should besinceDate
in function parameters.
– TheTiger
Mar 28 '18 at 6:14
@TheTiger - Thank you very much for highlighting the biggest mistake of this answer.. I'll practically test and update answer soon.
– Krunal
Mar 28 '18 at 7:14
1
My pleasure! I have tested it fordays
and it works fine.
– TheTiger
Mar 28 '18 at 7:15
1
Good answer. I’d only suggestfunc years(since date: Date) -> Int? { return Calendar.current.dateComponents[.year], from: date, to: self).years }
, and you could the call it aslet y = date1.years(since: date2)
. That might be more consistent with modern naming conventions.
– Rob
Feb 24 at 7:34
date
should be sinceDate
in function parameters.– TheTiger
Mar 28 '18 at 6:14
date
should be sinceDate
in function parameters.– TheTiger
Mar 28 '18 at 6:14
@TheTiger - Thank you very much for highlighting the biggest mistake of this answer.. I'll practically test and update answer soon.
– Krunal
Mar 28 '18 at 7:14
@TheTiger - Thank you very much for highlighting the biggest mistake of this answer.. I'll practically test and update answer soon.
– Krunal
Mar 28 '18 at 7:14
1
1
My pleasure! I have tested it for
days
and it works fine.– TheTiger
Mar 28 '18 at 7:15
My pleasure! I have tested it for
days
and it works fine.– TheTiger
Mar 28 '18 at 7:15
1
1
Good answer. I’d only suggest
func years(since date: Date) -> Int? { return Calendar.current.dateComponents[.year], from: date, to: self).years }
, and you could the call it as let y = date1.years(since: date2)
. That might be more consistent with modern naming conventions.– Rob
Feb 24 at 7:34
Good answer. I’d only suggest
func years(since date: Date) -> Int? { return Calendar.current.dateComponents[.year], from: date, to: self).years }
, and you could the call it as let y = date1.years(since: date2)
. That might be more consistent with modern naming conventions.– Rob
Feb 24 at 7:34
add a comment |
Update for Swift 3 iOS 10 Beta 4
func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
return components.day!
}
add a comment |
Update for Swift 3 iOS 10 Beta 4
func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
return components.day!
}
add a comment |
Update for Swift 3 iOS 10 Beta 4
func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
return components.day!
}
Update for Swift 3 iOS 10 Beta 4
func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
return components.day!
}
answered Aug 8 '16 at 14:23
ChaosSpeederChaosSpeeder
2,54442436
2,54442436
add a comment |
add a comment |
Here is the answer for Swift 3 (tested for IOS 10 Beta)
func daysBetweenDates(startDate: Date, endDate: Date) -> Int
{
let calendar = Calendar.current
let components = calendar.components([.day], from: startDate, to: endDate, options: )
return components.day!
}
Then you can call it like this
let pickedDate: Date = sender.date
let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
print("Num of Days: (NumOfDays)")
add a comment |
Here is the answer for Swift 3 (tested for IOS 10 Beta)
func daysBetweenDates(startDate: Date, endDate: Date) -> Int
{
let calendar = Calendar.current
let components = calendar.components([.day], from: startDate, to: endDate, options: )
return components.day!
}
Then you can call it like this
let pickedDate: Date = sender.date
let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
print("Num of Days: (NumOfDays)")
add a comment |
Here is the answer for Swift 3 (tested for IOS 10 Beta)
func daysBetweenDates(startDate: Date, endDate: Date) -> Int
{
let calendar = Calendar.current
let components = calendar.components([.day], from: startDate, to: endDate, options: )
return components.day!
}
Then you can call it like this
let pickedDate: Date = sender.date
let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
print("Num of Days: (NumOfDays)")
Here is the answer for Swift 3 (tested for IOS 10 Beta)
func daysBetweenDates(startDate: Date, endDate: Date) -> Int
{
let calendar = Calendar.current
let components = calendar.components([.day], from: startDate, to: endDate, options: )
return components.day!
}
Then you can call it like this
let pickedDate: Date = sender.date
let NumOfDays: Int = daysBetweenDates(startDate: pickedDate, endDate: Date())
print("Num of Days: (NumOfDays)")
edited Jul 24 '16 at 6:53
answered Jul 24 '16 at 6:44
kazantatarkazantatar
8114
8114
add a comment |
add a comment |
Swift 3. Thanks to Emin Buğra Saral above for the startOfDay
suggestion.
extension Date {
func daysBetween(date: Date) -> Int {
return Date.daysBetween(start: self, end: date)
}
static func daysBetween(start: Date, end: Date) -> Int {
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: start)
let date2 = calendar.startOfDay(for: end)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
}
Usage:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let start = dateFormatter.date(from: "2017-01-01")!
let end = dateFormatter.date(from: "2018-01-01")!
let diff = Date.daysBetween(start: start, end: end) // 365
1
it would definitely be better to move them both to noon, rather than 00:00 to avoid many problems.
– Fattie
Feb 21 '17 at 15:23
add a comment |
Swift 3. Thanks to Emin Buğra Saral above for the startOfDay
suggestion.
extension Date {
func daysBetween(date: Date) -> Int {
return Date.daysBetween(start: self, end: date)
}
static func daysBetween(start: Date, end: Date) -> Int {
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: start)
let date2 = calendar.startOfDay(for: end)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
}
Usage:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let start = dateFormatter.date(from: "2017-01-01")!
let end = dateFormatter.date(from: "2018-01-01")!
let diff = Date.daysBetween(start: start, end: end) // 365
1
it would definitely be better to move them both to noon, rather than 00:00 to avoid many problems.
– Fattie
Feb 21 '17 at 15:23
add a comment |
Swift 3. Thanks to Emin Buğra Saral above for the startOfDay
suggestion.
extension Date {
func daysBetween(date: Date) -> Int {
return Date.daysBetween(start: self, end: date)
}
static func daysBetween(start: Date, end: Date) -> Int {
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: start)
let date2 = calendar.startOfDay(for: end)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
}
Usage:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let start = dateFormatter.date(from: "2017-01-01")!
let end = dateFormatter.date(from: "2018-01-01")!
let diff = Date.daysBetween(start: start, end: end) // 365
Swift 3. Thanks to Emin Buğra Saral above for the startOfDay
suggestion.
extension Date {
func daysBetween(date: Date) -> Int {
return Date.daysBetween(start: self, end: date)
}
static func daysBetween(start: Date, end: Date) -> Int {
let calendar = Calendar.current
// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: start)
let date2 = calendar.startOfDay(for: end)
let a = calendar.dateComponents([.day], from: date1, to: date2)
return a.value(for: .day)!
}
}
Usage:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let start = dateFormatter.date(from: "2017-01-01")!
let end = dateFormatter.date(from: "2018-01-01")!
let diff = Date.daysBetween(start: start, end: end) // 365
edited May 23 '17 at 12:03
Community♦
11
11
answered Jan 22 '17 at 0:09
NormanNorman
654712
654712
1
it would definitely be better to move them both to noon, rather than 00:00 to avoid many problems.
– Fattie
Feb 21 '17 at 15:23
add a comment |
1
it would definitely be better to move them both to noon, rather than 00:00 to avoid many problems.
– Fattie
Feb 21 '17 at 15:23
1
1
it would definitely be better to move them both to noon, rather than 00:00 to avoid many problems.
– Fattie
Feb 21 '17 at 15:23
it would definitely be better to move them both to noon, rather than 00:00 to avoid many problems.
– Fattie
Feb 21 '17 at 15:23
add a comment |
The things built into swift are still very basic. As they should be at this early stage. But you can add your own stuff with the risk that comes with overloading operators and global domain functions. They will be local to your module though.
let now = NSDate()
let seventies = NSDate(timeIntervalSince1970: 0)
// Standard solution still works
let days = NSCalendar.currentCalendar().components(.CalendarUnitDay,
fromDate: seventies, toDate: now, options: nil).day
// Flashy swift... maybe...
func -(lhs:NSDate, rhs:NSDate) -> DateRange {
return DateRange(startDate: rhs, endDate: lhs)
}
class DateRange {
let startDate:NSDate
let endDate:NSDate
var calendar = NSCalendar.currentCalendar()
var days: Int {
return calendar.components(.CalendarUnitDay,
fromDate: startDate, toDate: endDate, options: nil).day
}
var months: Int {
return calendar.components(.CalendarUnitMonth,
fromDate: startDate, toDate: endDate, options: nil).month
}
init(startDate:NSDate, endDate:NSDate) {
self.startDate = startDate
self.endDate = endDate
}
}
// Now you can do this...
(now - seventies).months
(now - seventies).days
17
Don't use (24*60*60) for the length of a day. This does not take daylight saving time transitions into account.
– Martin R
Jul 13 '14 at 16:35
I think NSDate would adjust for that since it always uses GMT and daylight saving is just a formatting or localisation upon that. For sure it gets trickier for months, years or anything of really variable length though.
– Daniel Schlaug
Jul 13 '14 at 16:42
1
@MartinR I had to try it to believe it but indeed, now that I did I also saw that wikipedia mentions this. You are correct. Thanks for being stubborn with me.
– Daniel Schlaug
Jul 13 '14 at 22:01
1
There, edited to be correct. But the flashiness kind of went away.
– Daniel Schlaug
Jul 13 '14 at 22:17
1
it is defined by location, point of time and calendar system. the hebrew calendar has a leap month. there is a great wwdc video: performing calendar calculation — a must-see for every cocoa coder.
– vikingosegundo
Jul 14 '14 at 16:17
|
show 6 more comments
The things built into swift are still very basic. As they should be at this early stage. But you can add your own stuff with the risk that comes with overloading operators and global domain functions. They will be local to your module though.
let now = NSDate()
let seventies = NSDate(timeIntervalSince1970: 0)
// Standard solution still works
let days = NSCalendar.currentCalendar().components(.CalendarUnitDay,
fromDate: seventies, toDate: now, options: nil).day
// Flashy swift... maybe...
func -(lhs:NSDate, rhs:NSDate) -> DateRange {
return DateRange(startDate: rhs, endDate: lhs)
}
class DateRange {
let startDate:NSDate
let endDate:NSDate
var calendar = NSCalendar.currentCalendar()
var days: Int {
return calendar.components(.CalendarUnitDay,
fromDate: startDate, toDate: endDate, options: nil).day
}
var months: Int {
return calendar.components(.CalendarUnitMonth,
fromDate: startDate, toDate: endDate, options: nil).month
}
init(startDate:NSDate, endDate:NSDate) {
self.startDate = startDate
self.endDate = endDate
}
}
// Now you can do this...
(now - seventies).months
(now - seventies).days
17
Don't use (24*60*60) for the length of a day. This does not take daylight saving time transitions into account.
– Martin R
Jul 13 '14 at 16:35
I think NSDate would adjust for that since it always uses GMT and daylight saving is just a formatting or localisation upon that. For sure it gets trickier for months, years or anything of really variable length though.
– Daniel Schlaug
Jul 13 '14 at 16:42
1
@MartinR I had to try it to believe it but indeed, now that I did I also saw that wikipedia mentions this. You are correct. Thanks for being stubborn with me.
– Daniel Schlaug
Jul 13 '14 at 22:01
1
There, edited to be correct. But the flashiness kind of went away.
– Daniel Schlaug
Jul 13 '14 at 22:17
1
it is defined by location, point of time and calendar system. the hebrew calendar has a leap month. there is a great wwdc video: performing calendar calculation — a must-see for every cocoa coder.
– vikingosegundo
Jul 14 '14 at 16:17
|
show 6 more comments
The things built into swift are still very basic. As they should be at this early stage. But you can add your own stuff with the risk that comes with overloading operators and global domain functions. They will be local to your module though.
let now = NSDate()
let seventies = NSDate(timeIntervalSince1970: 0)
// Standard solution still works
let days = NSCalendar.currentCalendar().components(.CalendarUnitDay,
fromDate: seventies, toDate: now, options: nil).day
// Flashy swift... maybe...
func -(lhs:NSDate, rhs:NSDate) -> DateRange {
return DateRange(startDate: rhs, endDate: lhs)
}
class DateRange {
let startDate:NSDate
let endDate:NSDate
var calendar = NSCalendar.currentCalendar()
var days: Int {
return calendar.components(.CalendarUnitDay,
fromDate: startDate, toDate: endDate, options: nil).day
}
var months: Int {
return calendar.components(.CalendarUnitMonth,
fromDate: startDate, toDate: endDate, options: nil).month
}
init(startDate:NSDate, endDate:NSDate) {
self.startDate = startDate
self.endDate = endDate
}
}
// Now you can do this...
(now - seventies).months
(now - seventies).days
The things built into swift are still very basic. As they should be at this early stage. But you can add your own stuff with the risk that comes with overloading operators and global domain functions. They will be local to your module though.
let now = NSDate()
let seventies = NSDate(timeIntervalSince1970: 0)
// Standard solution still works
let days = NSCalendar.currentCalendar().components(.CalendarUnitDay,
fromDate: seventies, toDate: now, options: nil).day
// Flashy swift... maybe...
func -(lhs:NSDate, rhs:NSDate) -> DateRange {
return DateRange(startDate: rhs, endDate: lhs)
}
class DateRange {
let startDate:NSDate
let endDate:NSDate
var calendar = NSCalendar.currentCalendar()
var days: Int {
return calendar.components(.CalendarUnitDay,
fromDate: startDate, toDate: endDate, options: nil).day
}
var months: Int {
return calendar.components(.CalendarUnitMonth,
fromDate: startDate, toDate: endDate, options: nil).month
}
init(startDate:NSDate, endDate:NSDate) {
self.startDate = startDate
self.endDate = endDate
}
}
// Now you can do this...
(now - seventies).months
(now - seventies).days
edited Jul 13 '14 at 22:46
answered Jul 13 '14 at 16:33
Daniel SchlaugDaniel Schlaug
1,1791015
1,1791015
17
Don't use (24*60*60) for the length of a day. This does not take daylight saving time transitions into account.
– Martin R
Jul 13 '14 at 16:35
I think NSDate would adjust for that since it always uses GMT and daylight saving is just a formatting or localisation upon that. For sure it gets trickier for months, years or anything of really variable length though.
– Daniel Schlaug
Jul 13 '14 at 16:42
1
@MartinR I had to try it to believe it but indeed, now that I did I also saw that wikipedia mentions this. You are correct. Thanks for being stubborn with me.
– Daniel Schlaug
Jul 13 '14 at 22:01
1
There, edited to be correct. But the flashiness kind of went away.
– Daniel Schlaug
Jul 13 '14 at 22:17
1
it is defined by location, point of time and calendar system. the hebrew calendar has a leap month. there is a great wwdc video: performing calendar calculation — a must-see for every cocoa coder.
– vikingosegundo
Jul 14 '14 at 16:17
|
show 6 more comments
17
Don't use (24*60*60) for the length of a day. This does not take daylight saving time transitions into account.
– Martin R
Jul 13 '14 at 16:35
I think NSDate would adjust for that since it always uses GMT and daylight saving is just a formatting or localisation upon that. For sure it gets trickier for months, years or anything of really variable length though.
– Daniel Schlaug
Jul 13 '14 at 16:42
1
@MartinR I had to try it to believe it but indeed, now that I did I also saw that wikipedia mentions this. You are correct. Thanks for being stubborn with me.
– Daniel Schlaug
Jul 13 '14 at 22:01
1
There, edited to be correct. But the flashiness kind of went away.
– Daniel Schlaug
Jul 13 '14 at 22:17
1
it is defined by location, point of time and calendar system. the hebrew calendar has a leap month. there is a great wwdc video: performing calendar calculation — a must-see for every cocoa coder.
– vikingosegundo
Jul 14 '14 at 16:17
17
17
Don't use (24*60*60) for the length of a day. This does not take daylight saving time transitions into account.
– Martin R
Jul 13 '14 at 16:35
Don't use (24*60*60) for the length of a day. This does not take daylight saving time transitions into account.
– Martin R
Jul 13 '14 at 16:35
I think NSDate would adjust for that since it always uses GMT and daylight saving is just a formatting or localisation upon that. For sure it gets trickier for months, years or anything of really variable length though.
– Daniel Schlaug
Jul 13 '14 at 16:42
I think NSDate would adjust for that since it always uses GMT and daylight saving is just a formatting or localisation upon that. For sure it gets trickier for months, years or anything of really variable length though.
– Daniel Schlaug
Jul 13 '14 at 16:42
1
1
@MartinR I had to try it to believe it but indeed, now that I did I also saw that wikipedia mentions this. You are correct. Thanks for being stubborn with me.
– Daniel Schlaug
Jul 13 '14 at 22:01
@MartinR I had to try it to believe it but indeed, now that I did I also saw that wikipedia mentions this. You are correct. Thanks for being stubborn with me.
– Daniel Schlaug
Jul 13 '14 at 22:01
1
1
There, edited to be correct. But the flashiness kind of went away.
– Daniel Schlaug
Jul 13 '14 at 22:17
There, edited to be correct. But the flashiness kind of went away.
– Daniel Schlaug
Jul 13 '14 at 22:17
1
1
it is defined by location, point of time and calendar system. the hebrew calendar has a leap month. there is a great wwdc video: performing calendar calculation — a must-see for every cocoa coder.
– vikingosegundo
Jul 14 '14 at 16:17
it is defined by location, point of time and calendar system. the hebrew calendar has a leap month. there is a great wwdc video: performing calendar calculation — a must-see for every cocoa coder.
– vikingosegundo
Jul 14 '14 at 16:17
|
show 6 more comments
Here is my answer for Swift 3:
func daysBetweenDates(startDate: NSDate, endDate: NSDate, inTimeZone timeZone: TimeZone? = nil) -> Int {
var calendar = Calendar.current
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
let dateComponents = calendar.dateComponents([.day], from: startDate.startOfDay, to: endDate.startOfDay)
return dateComponents.day!
}
add a comment |
Here is my answer for Swift 3:
func daysBetweenDates(startDate: NSDate, endDate: NSDate, inTimeZone timeZone: TimeZone? = nil) -> Int {
var calendar = Calendar.current
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
let dateComponents = calendar.dateComponents([.day], from: startDate.startOfDay, to: endDate.startOfDay)
return dateComponents.day!
}
add a comment |
Here is my answer for Swift 3:
func daysBetweenDates(startDate: NSDate, endDate: NSDate, inTimeZone timeZone: TimeZone? = nil) -> Int {
var calendar = Calendar.current
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
let dateComponents = calendar.dateComponents([.day], from: startDate.startOfDay, to: endDate.startOfDay)
return dateComponents.day!
}
Here is my answer for Swift 3:
func daysBetweenDates(startDate: NSDate, endDate: NSDate, inTimeZone timeZone: TimeZone? = nil) -> Int {
var calendar = Calendar.current
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
let dateComponents = calendar.dateComponents([.day], from: startDate.startOfDay, to: endDate.startOfDay)
return dateComponents.day!
}
answered Oct 2 '16 at 2:29
Alen LiangAlen Liang
315310
315310
add a comment |
add a comment |
There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.
It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.
add a comment |
There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.
It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.
add a comment |
There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.
It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.
There's hardly any Swift-specific standard library yet; just the lean basic numeric, string, and collection types.
It's perfectly possible to define such shorthands using extensions, but as far as the actual out-of-the-box APIs goes, there is no "new" Cocoa; Swift just maps directly to the same old verbose Cocoa APIs as they already exist.
answered Jul 13 '14 at 16:36
Wes CampaigneWes Campaigne
2,44121416
2,44121416
add a comment |
add a comment |
I'm going to add my version even though this thread is a year old. My code looks like this:
var name = txtName.stringValue // Get the users name
// Get the date components from the window controls
var dateComponents = NSDateComponents()
dateComponents.day = txtDOBDay.integerValue
dateComponents.month = txtDOBMonth.integerValue
dateComponents.year = txtDOBYear.integerValue
// Make a Gregorian calendar
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
// Get the two dates we need
var birthdate = calendar?.dateFromComponents(dateComponents)
let currentDate = NSDate()
var durationDateComponents = calendar?.components(NSCalendarUnit.CalendarUnitDay, fromDate: birthdate!, toDate: currentDate, options: nil)
let numberOfDaysAlive = durationDateComponents?.day
println("(numberOfDaysAlive!)")
txtGreeting.stringValue = "Hello (name), You have been alive for (numberOfDaysAlive!) days."
I hope it helps someone.
Cheers,
add a comment |
I'm going to add my version even though this thread is a year old. My code looks like this:
var name = txtName.stringValue // Get the users name
// Get the date components from the window controls
var dateComponents = NSDateComponents()
dateComponents.day = txtDOBDay.integerValue
dateComponents.month = txtDOBMonth.integerValue
dateComponents.year = txtDOBYear.integerValue
// Make a Gregorian calendar
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
// Get the two dates we need
var birthdate = calendar?.dateFromComponents(dateComponents)
let currentDate = NSDate()
var durationDateComponents = calendar?.components(NSCalendarUnit.CalendarUnitDay, fromDate: birthdate!, toDate: currentDate, options: nil)
let numberOfDaysAlive = durationDateComponents?.day
println("(numberOfDaysAlive!)")
txtGreeting.stringValue = "Hello (name), You have been alive for (numberOfDaysAlive!) days."
I hope it helps someone.
Cheers,
add a comment |
I'm going to add my version even though this thread is a year old. My code looks like this:
var name = txtName.stringValue // Get the users name
// Get the date components from the window controls
var dateComponents = NSDateComponents()
dateComponents.day = txtDOBDay.integerValue
dateComponents.month = txtDOBMonth.integerValue
dateComponents.year = txtDOBYear.integerValue
// Make a Gregorian calendar
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
// Get the two dates we need
var birthdate = calendar?.dateFromComponents(dateComponents)
let currentDate = NSDate()
var durationDateComponents = calendar?.components(NSCalendarUnit.CalendarUnitDay, fromDate: birthdate!, toDate: currentDate, options: nil)
let numberOfDaysAlive = durationDateComponents?.day
println("(numberOfDaysAlive!)")
txtGreeting.stringValue = "Hello (name), You have been alive for (numberOfDaysAlive!) days."
I hope it helps someone.
Cheers,
I'm going to add my version even though this thread is a year old. My code looks like this:
var name = txtName.stringValue // Get the users name
// Get the date components from the window controls
var dateComponents = NSDateComponents()
dateComponents.day = txtDOBDay.integerValue
dateComponents.month = txtDOBMonth.integerValue
dateComponents.year = txtDOBYear.integerValue
// Make a Gregorian calendar
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
// Get the two dates we need
var birthdate = calendar?.dateFromComponents(dateComponents)
let currentDate = NSDate()
var durationDateComponents = calendar?.components(NSCalendarUnit.CalendarUnitDay, fromDate: birthdate!, toDate: currentDate, options: nil)
let numberOfDaysAlive = durationDateComponents?.day
println("(numberOfDaysAlive!)")
txtGreeting.stringValue = "Hello (name), You have been alive for (numberOfDaysAlive!) days."
I hope it helps someone.
Cheers,
answered Jul 8 '15 at 10:47
Andrew HAndrew H
355621
355621
add a comment |
add a comment |
Erin's method updated to Swift 3, This shows days from today (disregarding time of day)
func daysBetweenDates( endDate: Date) -> Int
let calendar: Calendar = Calendar.current
let date1 = calendar.startOfDay(for: Date())
let date2 = calendar.startOfDay(for: secondDate)
return calendar.dateComponents([.day], from: date1, to: date2).day!
}
add a comment |
Erin's method updated to Swift 3, This shows days from today (disregarding time of day)
func daysBetweenDates( endDate: Date) -> Int
let calendar: Calendar = Calendar.current
let date1 = calendar.startOfDay(for: Date())
let date2 = calendar.startOfDay(for: secondDate)
return calendar.dateComponents([.day], from: date1, to: date2).day!
}
add a comment |
Erin's method updated to Swift 3, This shows days from today (disregarding time of day)
func daysBetweenDates( endDate: Date) -> Int
let calendar: Calendar = Calendar.current
let date1 = calendar.startOfDay(for: Date())
let date2 = calendar.startOfDay(for: secondDate)
return calendar.dateComponents([.day], from: date1, to: date2).day!
}
Erin's method updated to Swift 3, This shows days from today (disregarding time of day)
func daysBetweenDates( endDate: Date) -> Int
let calendar: Calendar = Calendar.current
let date1 = calendar.startOfDay(for: Date())
let date2 = calendar.startOfDay(for: secondDate)
return calendar.dateComponents([.day], from: date1, to: date2).day!
}
edited Aug 28 '16 at 14:31
answered Aug 28 '16 at 14:02
Peter JohnsonPeter Johnson
3,31411724
3,31411724
add a comment |
add a comment |
Swift 3.2
extension DateComponentsFormatter {
func difference(from fromDate: Date, to toDate: Date) -> String? {
self.allowedUnits = [.year,.month,.weekOfMonth,.day]
self.maximumUnitCount = 1
self.unitsStyle = .full
return self.string(from: fromDate, to: toDate)
}
}
add a comment |
Swift 3.2
extension DateComponentsFormatter {
func difference(from fromDate: Date, to toDate: Date) -> String? {
self.allowedUnits = [.year,.month,.weekOfMonth,.day]
self.maximumUnitCount = 1
self.unitsStyle = .full
return self.string(from: fromDate, to: toDate)
}
}
add a comment |
Swift 3.2
extension DateComponentsFormatter {
func difference(from fromDate: Date, to toDate: Date) -> String? {
self.allowedUnits = [.year,.month,.weekOfMonth,.day]
self.maximumUnitCount = 1
self.unitsStyle = .full
return self.string(from: fromDate, to: toDate)
}
}
Swift 3.2
extension DateComponentsFormatter {
func difference(from fromDate: Date, to toDate: Date) -> String? {
self.allowedUnits = [.year,.month,.weekOfMonth,.day]
self.maximumUnitCount = 1
self.unitsStyle = .full
return self.string(from: fromDate, to: toDate)
}
}
answered Jun 12 '17 at 8:07
Adam SmakaAdam Smaka
2,32312031
2,32312031
add a comment |
add a comment |
All answer is good. But for Localizations we need calculates a number of decimal days in between two dates. so we can provide the sustainable decimal format.
// This method returns the fractional number of days between to dates
func getFractionalDaysBetweenDates(date1: Date, date2: Date) -> Double {
let components = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)
var decimalDays = Double(components.day!)
decimalDays += Double(components.hour!) / 24.0
return decimalDays
}
add a comment |
All answer is good. But for Localizations we need calculates a number of decimal days in between two dates. so we can provide the sustainable decimal format.
// This method returns the fractional number of days between to dates
func getFractionalDaysBetweenDates(date1: Date, date2: Date) -> Double {
let components = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)
var decimalDays = Double(components.day!)
decimalDays += Double(components.hour!) / 24.0
return decimalDays
}
add a comment |
All answer is good. But for Localizations we need calculates a number of decimal days in between two dates. so we can provide the sustainable decimal format.
// This method returns the fractional number of days between to dates
func getFractionalDaysBetweenDates(date1: Date, date2: Date) -> Double {
let components = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)
var decimalDays = Double(components.day!)
decimalDays += Double(components.hour!) / 24.0
return decimalDays
}
All answer is good. But for Localizations we need calculates a number of decimal days in between two dates. so we can provide the sustainable decimal format.
// This method returns the fractional number of days between to dates
func getFractionalDaysBetweenDates(date1: Date, date2: Date) -> Double {
let components = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)
var decimalDays = Double(components.day!)
decimalDays += Double(components.hour!) / 24.0
return decimalDays
}
answered Mar 11 '18 at 20:15
Durul DalkanatDurul Dalkanat
5,12632733
5,12632733
add a comment |
add a comment |
Swift 3 - Days from today until date
func daysUntilDate(endDateComponents: DateComponents) -> Int
{
let cal = Calendar.current
var components = cal.dateComponents([.era, .year, .month, .day], from: NSDate() as Date)
let today = cal.date(from: components)
let otherDate = cal.date(from: endDateComponents)
components = cal.dateComponents([Calendar.Component.day], from: (today! as Date), to: otherDate!)
return components.day!
}
Call function like this
// Days from today until date
var examnDate = DateComponents()
examnDate.year = 2016
examnDate.month = 12
examnDate.day = 15
let daysCount = daysUntilDate(endDateComponents: examnDate)
add a comment |
Swift 3 - Days from today until date
func daysUntilDate(endDateComponents: DateComponents) -> Int
{
let cal = Calendar.current
var components = cal.dateComponents([.era, .year, .month, .day], from: NSDate() as Date)
let today = cal.date(from: components)
let otherDate = cal.date(from: endDateComponents)
components = cal.dateComponents([Calendar.Component.day], from: (today! as Date), to: otherDate!)
return components.day!
}
Call function like this
// Days from today until date
var examnDate = DateComponents()
examnDate.year = 2016
examnDate.month = 12
examnDate.day = 15
let daysCount = daysUntilDate(endDateComponents: examnDate)
add a comment |
Swift 3 - Days from today until date
func daysUntilDate(endDateComponents: DateComponents) -> Int
{
let cal = Calendar.current
var components = cal.dateComponents([.era, .year, .month, .day], from: NSDate() as Date)
let today = cal.date(from: components)
let otherDate = cal.date(from: endDateComponents)
components = cal.dateComponents([Calendar.Component.day], from: (today! as Date), to: otherDate!)
return components.day!
}
Call function like this
// Days from today until date
var examnDate = DateComponents()
examnDate.year = 2016
examnDate.month = 12
examnDate.day = 15
let daysCount = daysUntilDate(endDateComponents: examnDate)
Swift 3 - Days from today until date
func daysUntilDate(endDateComponents: DateComponents) -> Int
{
let cal = Calendar.current
var components = cal.dateComponents([.era, .year, .month, .day], from: NSDate() as Date)
let today = cal.date(from: components)
let otherDate = cal.date(from: endDateComponents)
components = cal.dateComponents([Calendar.Component.day], from: (today! as Date), to: otherDate!)
return components.day!
}
Call function like this
// Days from today until date
var examnDate = DateComponents()
examnDate.year = 2016
examnDate.month = 12
examnDate.day = 15
let daysCount = daysUntilDate(endDateComponents: examnDate)
answered Nov 23 '16 at 23:46
karenmskarenms
1,3481317
1,3481317
add a comment |
add a comment |
easier option would be to create a extension on Date
public extension Date {
public var currentCalendar: Calendar {
return Calendar.autoupdatingCurrent
}
public func daysBetween(_ date: Date) -> Int {
let components = currentCalendar.dateComponents([.day], from: self, to: date)
return components.day!
}
}
add a comment |
easier option would be to create a extension on Date
public extension Date {
public var currentCalendar: Calendar {
return Calendar.autoupdatingCurrent
}
public func daysBetween(_ date: Date) -> Int {
let components = currentCalendar.dateComponents([.day], from: self, to: date)
return components.day!
}
}
add a comment |
easier option would be to create a extension on Date
public extension Date {
public var currentCalendar: Calendar {
return Calendar.autoupdatingCurrent
}
public func daysBetween(_ date: Date) -> Int {
let components = currentCalendar.dateComponents([.day], from: self, to: date)
return components.day!
}
}
easier option would be to create a extension on Date
public extension Date {
public var currentCalendar: Calendar {
return Calendar.autoupdatingCurrent
}
public func daysBetween(_ date: Date) -> Int {
let components = currentCalendar.dateComponents([.day], from: self, to: date)
return components.day!
}
}
answered Jan 11 '17 at 10:23
Suhit PatilSuhit Patil
7,24922643
7,24922643
add a comment |
add a comment |
func completeOffset(from date:Date) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief
return formatter.string(from: Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date, to: self))
}
if you need year month days and hours as string use this
var tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
let dc = tomorrow.completeOffset(from: Date())
add a comment |
func completeOffset(from date:Date) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief
return formatter.string(from: Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date, to: self))
}
if you need year month days and hours as string use this
var tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
let dc = tomorrow.completeOffset(from: Date())
add a comment |
func completeOffset(from date:Date) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief
return formatter.string(from: Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date, to: self))
}
if you need year month days and hours as string use this
var tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
let dc = tomorrow.completeOffset(from: Date())
func completeOffset(from date:Date) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief
return formatter.string(from: Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date, to: self))
}
if you need year month days and hours as string use this
var tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())!
let dc = tomorrow.completeOffset(from: Date())
answered Mar 15 '18 at 18:27
Akash ShindheAkash Shindhe
209212
209212
add a comment |
add a comment |
Nice handy one liner :
extension Date {
var daysFromNow: Int {
return Calendar.current.dateComponents([.day], from: Date(), to: self).day!
}
}
add a comment |
Nice handy one liner :
extension Date {
var daysFromNow: Int {
return Calendar.current.dateComponents([.day], from: Date(), to: self).day!
}
}
add a comment |
Nice handy one liner :
extension Date {
var daysFromNow: Int {
return Calendar.current.dateComponents([.day], from: Date(), to: self).day!
}
}
Nice handy one liner :
extension Date {
var daysFromNow: Int {
return Calendar.current.dateComponents([.day], from: Date(), to: self).day!
}
}
answered Jul 5 '18 at 23:54
Rom.Rom.
2,11421117
2,11421117
add a comment |
add a comment |
This returns an absolute difference in days between some Date
and today:
extension Date {
func daysFromToday() -> Int {
return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)
}
}
and then use it:
if someDate.daysFromToday() >= 7 {
// at least a week from today
}
add a comment |
This returns an absolute difference in days between some Date
and today:
extension Date {
func daysFromToday() -> Int {
return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)
}
}
and then use it:
if someDate.daysFromToday() >= 7 {
// at least a week from today
}
add a comment |
This returns an absolute difference in days between some Date
and today:
extension Date {
func daysFromToday() -> Int {
return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)
}
}
and then use it:
if someDate.daysFromToday() >= 7 {
// at least a week from today
}
This returns an absolute difference in days between some Date
and today:
extension Date {
func daysFromToday() -> Int {
return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)
}
}
and then use it:
if someDate.daysFromToday() >= 7 {
// at least a week from today
}
answered Aug 10 '18 at 17:15
budidinobudidino
6,27156168
6,27156168
add a comment |
add a comment |
Swift 4
func getDateHeader(indexPath: Int) -> String {
let formatter2 = DateFormatter()
formatter2.dateFormat = "MM-dd-yyyy"
var dateDeadline : Date?
dateDeadline = formatter2.date(from: arrCompletedDate[indexPath] as! String)
let currentTime = dateDeadline?.unixTimestamp
let calendar = NSCalendar.current
let date = NSDate(timeIntervalSince1970: Double(currentTime!))
if calendar.isDateInYesterday(date as Date) { return "Yesterday" }
else if calendar.isDateInToday(date as Date) { return "Today" }
else if calendar.isDateInTomorrow(date as Date) { return "Tomorrow" }
else {
let startOfNow = calendar.startOfDay(for: NSDate() as Date)
let startOfTimeStamp = calendar.startOfDay(for: date as Date)
let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
let day = components.day!
if day < 1 { return "(abs(day)) days ago" }
else { return "In (day) days" }
}
}
add a comment |
Swift 4
func getDateHeader(indexPath: Int) -> String {
let formatter2 = DateFormatter()
formatter2.dateFormat = "MM-dd-yyyy"
var dateDeadline : Date?
dateDeadline = formatter2.date(from: arrCompletedDate[indexPath] as! String)
let currentTime = dateDeadline?.unixTimestamp
let calendar = NSCalendar.current
let date = NSDate(timeIntervalSince1970: Double(currentTime!))
if calendar.isDateInYesterday(date as Date) { return "Yesterday" }
else if calendar.isDateInToday(date as Date) { return "Today" }
else if calendar.isDateInTomorrow(date as Date) { return "Tomorrow" }
else {
let startOfNow = calendar.startOfDay(for: NSDate() as Date)
let startOfTimeStamp = calendar.startOfDay(for: date as Date)
let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
let day = components.day!
if day < 1 { return "(abs(day)) days ago" }
else { return "In (day) days" }
}
}
add a comment |
Swift 4
func getDateHeader(indexPath: Int) -> String {
let formatter2 = DateFormatter()
formatter2.dateFormat = "MM-dd-yyyy"
var dateDeadline : Date?
dateDeadline = formatter2.date(from: arrCompletedDate[indexPath] as! String)
let currentTime = dateDeadline?.unixTimestamp
let calendar = NSCalendar.current
let date = NSDate(timeIntervalSince1970: Double(currentTime!))
if calendar.isDateInYesterday(date as Date) { return "Yesterday" }
else if calendar.isDateInToday(date as Date) { return "Today" }
else if calendar.isDateInTomorrow(date as Date) { return "Tomorrow" }
else {
let startOfNow = calendar.startOfDay(for: NSDate() as Date)
let startOfTimeStamp = calendar.startOfDay(for: date as Date)
let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
let day = components.day!
if day < 1 { return "(abs(day)) days ago" }
else { return "In (day) days" }
}
}
Swift 4
func getDateHeader(indexPath: Int) -> String {
let formatter2 = DateFormatter()
formatter2.dateFormat = "MM-dd-yyyy"
var dateDeadline : Date?
dateDeadline = formatter2.date(from: arrCompletedDate[indexPath] as! String)
let currentTime = dateDeadline?.unixTimestamp
let calendar = NSCalendar.current
let date = NSDate(timeIntervalSince1970: Double(currentTime!))
if calendar.isDateInYesterday(date as Date) { return "Yesterday" }
else if calendar.isDateInToday(date as Date) { return "Today" }
else if calendar.isDateInTomorrow(date as Date) { return "Tomorrow" }
else {
let startOfNow = calendar.startOfDay(for: NSDate() as Date)
let startOfTimeStamp = calendar.startOfDay(for: date as Date)
let components = calendar.dateComponents([.day], from: startOfNow, to: startOfTimeStamp)
let day = components.day!
if day < 1 { return "(abs(day)) days ago" }
else { return "In (day) days" }
}
}
answered Oct 26 '18 at 7:37
Niraj PaulNiraj Paul
391216
391216
add a comment |
add a comment |
let calendar = NSCalendar.currentCalendar();
let component1 = calendar.component(.Day, fromDate: fromDate)
let component2 = calendar.component(.Day, fromDate: toDate)
let difference = component1 - component2
1
that measures the difference between the number portion of the dates- I.e. 21st January to 22nd of February will give 1 day, not 32 days as it should
– Peter Johnson
Aug 28 '16 at 14:16
add a comment |
let calendar = NSCalendar.currentCalendar();
let component1 = calendar.component(.Day, fromDate: fromDate)
let component2 = calendar.component(.Day, fromDate: toDate)
let difference = component1 - component2
1
that measures the difference between the number portion of the dates- I.e. 21st January to 22nd of February will give 1 day, not 32 days as it should
– Peter Johnson
Aug 28 '16 at 14:16
add a comment |
let calendar = NSCalendar.currentCalendar();
let component1 = calendar.component(.Day, fromDate: fromDate)
let component2 = calendar.component(.Day, fromDate: toDate)
let difference = component1 - component2
let calendar = NSCalendar.currentCalendar();
let component1 = calendar.component(.Day, fromDate: fromDate)
let component2 = calendar.component(.Day, fromDate: toDate)
let difference = component1 - component2
answered Jul 1 '16 at 6:35
Raj AggrawalRaj Aggrawal
476417
476417
1
that measures the difference between the number portion of the dates- I.e. 21st January to 22nd of February will give 1 day, not 32 days as it should
– Peter Johnson
Aug 28 '16 at 14:16
add a comment |
1
that measures the difference between the number portion of the dates- I.e. 21st January to 22nd of February will give 1 day, not 32 days as it should
– Peter Johnson
Aug 28 '16 at 14:16
1
1
that measures the difference between the number portion of the dates- I.e. 21st January to 22nd of February will give 1 day, not 32 days as it should
– Peter Johnson
Aug 28 '16 at 14:16
that measures the difference between the number portion of the dates- I.e. 21st January to 22nd of February will give 1 day, not 32 days as it should
– Peter Johnson
Aug 28 '16 at 14:16
add a comment |
2017 version, copy and paste
func simpleIndex(ofDate: Date) -> Int {
// index here just means today 0, yesterday -1, tomorrow 1 etc.
let c = Calendar.current
let todayRightNow = Date()
let d = c.date(bySetting: .hour, value: 13, of: ofDate)
let t = c.date(bySetting: .hour, value: 13, of: todayRightNow)
if d == nil || today == nil {
print("weird problem simpleIndex#ofDate")
return 0
}
let r = c.dateComponents([.day], from: today!, to: d!)
// yesterday is negative one, tomorrow is one
if let o = r.value(for: .day) {
return o
}
else {
print("another weird problem simpleIndex#ofDate")
return 0
}
}
add a comment |
2017 version, copy and paste
func simpleIndex(ofDate: Date) -> Int {
// index here just means today 0, yesterday -1, tomorrow 1 etc.
let c = Calendar.current
let todayRightNow = Date()
let d = c.date(bySetting: .hour, value: 13, of: ofDate)
let t = c.date(bySetting: .hour, value: 13, of: todayRightNow)
if d == nil || today == nil {
print("weird problem simpleIndex#ofDate")
return 0
}
let r = c.dateComponents([.day], from: today!, to: d!)
// yesterday is negative one, tomorrow is one
if let o = r.value(for: .day) {
return o
}
else {
print("another weird problem simpleIndex#ofDate")
return 0
}
}
add a comment |
2017 version, copy and paste
func simpleIndex(ofDate: Date) -> Int {
// index here just means today 0, yesterday -1, tomorrow 1 etc.
let c = Calendar.current
let todayRightNow = Date()
let d = c.date(bySetting: .hour, value: 13, of: ofDate)
let t = c.date(bySetting: .hour, value: 13, of: todayRightNow)
if d == nil || today == nil {
print("weird problem simpleIndex#ofDate")
return 0
}
let r = c.dateComponents([.day], from: today!, to: d!)
// yesterday is negative one, tomorrow is one
if let o = r.value(for: .day) {
return o
}
else {
print("another weird problem simpleIndex#ofDate")
return 0
}
}
2017 version, copy and paste
func simpleIndex(ofDate: Date) -> Int {
// index here just means today 0, yesterday -1, tomorrow 1 etc.
let c = Calendar.current
let todayRightNow = Date()
let d = c.date(bySetting: .hour, value: 13, of: ofDate)
let t = c.date(bySetting: .hour, value: 13, of: todayRightNow)
if d == nil || today == nil {
print("weird problem simpleIndex#ofDate")
return 0
}
let r = c.dateComponents([.day], from: today!, to: d!)
// yesterday is negative one, tomorrow is one
if let o = r.value(for: .day) {
return o
}
else {
print("another weird problem simpleIndex#ofDate")
return 0
}
}
edited Jul 29 '17 at 13:11
answered Jul 20 '17 at 23:00
FattieFattie
20.5k31209455
20.5k31209455
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24723431%2fswift-days-between-two-nsdates%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
I think you still have to use NSCalendar and NSDateComponents (for which there must be hundreds of answers on SO). - If you are looking for something "new and awesome possibility" then it would be helpful to show your present solution for comparison.
– Martin R
Jul 13 '14 at 14:15
1
This is now very easy, and you don't have to use "NS" anything. I typed in an answer for 2017, to copy and paste.
– Fattie
Jul 20 '17 at 23:00