How to get the today's and tomorrow's date in swift 4
I would do this with components.
Assuming you need time in seconds as defined by time(2)
. If you need in milliseconds as defined by time(3)
, then you can multiply it out by 1000.
// Get right now as it's `DateComponents`.
let now = Calendar.current.dateComponents(in: .current, from: Date())
// Create the start of the day in `DateComponents` by leaving off the time.
let today = DateComponents(year: now.year, month: now.month, day: now.day)
let dateToday = Calendar.current.date(from: today)!
print(dateToday.timeIntervalSince1970)
// Add 1 to the day to get tomorrow.
// Don't worry about month and year wraps, the API handles that.
let tomorrow = DateComponents(year: now.year, month: now.month, day: now.day! + 1)
let dateTomorrow = Calendar.current.date(from: tomorrow)!
print(dateTomorrow.timeIntervalSince1970)
You can get yesterday by subtracting 1.
If you need this in the universal time (UTC, GMT, Z… whatever name you give universal time), then use the following.
let utc = TimeZone(abbreviation: "UTC")!
let now = Calendar.current.dateComponents(in: utc, from: Date())
swift 3 how to get date for tomorrow and yesterday ( take care special case ) new month or new year
You should use Calendar method date(byAdding component:)
to do your calendrical calculations using noon time. Doing so you don't need to worry about those special cases:
Swift 3 or Later
extension Date {
static var yesterday: Date { return Date().dayBefore }
static var tomorrow: Date { return Date().dayAfter }
var dayBefore: Date {
return Calendar.current.date(byAdding: .day, value: -1, to: noon)!
}
var dayAfter: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
}
var noon: Date {
return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
var month: Int {
return Calendar.current.component(.month, from: self)
}
var isLastDayOfMonth: Bool {
return dayAfter.month != month
}
}
Date.yesterday // "Oct 28, 2018 at 12:00 PM"
Date() // "Oct 29, 2018 at 11:01 AM"
Date.tomorrow // "Oct 30, 2018 at 12:00 PM"
Date.tomorrow.month // 10
Date().isLastDayOfMonth // false
Date format in Swift TODAY TOMORROW YESTERDAY
The DateFormatter doesn't behave well when setting doesRelativeDateFormatting = true
and trying to apply a custom format at the same time. So the easiest solution is to use the format given by a Style
and a Locale
let relativeDateFormatter = DateFormatter()
relativeDateFormatter.timeStyle = .none
relativeDateFormatter.dateStyle = .medium
relativeDateFormatter.locale = Locale(identifier: "en_GB")
relativeDateFormatter.doesRelativeDateFormatting = true
Example
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yyyy-MM-dd"
let dates = ["2020-09-01", "2020-09-15", "2020-09-16", "2020-09-30"].compactMap { inputFormatter.date(from: $0)}
for date in dates {
print(relativeDateFormatter.string(from: date))
}
1 Sep 2020
Yesterday
Today
30 Sep 2020
Now if you want to apply a custom format I have not found a solution for this when using the same DateFormatter instance so we need to create a new one for the custom format and use it together with a check so we apply the custom format only when it is not Today etc
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM dd"
for date in dates {
let string = relativeDateFormatter.string(from: date)
if let _ = string.rangeOfCharacter(from: .decimalDigits) {
print(dateFormatter.string(from: date))
} else {
print(string)
}
}
Tuesday, Sep 01
Yesterday
Today
Wednesday, Sep 30
Set Tomorrow Date from custom date swift
import Foundation
extension Date {
var tomorrow: Date? {
return Calendar.current.date(byAdding: .day, value: 1, to: self)
}
}
let today = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy, HH:mm b"
if let tomorrow = today.tomorrow {
let tomorrowString = dateFormatter.string(from: tomorrow)
print("\(tomorrowString)" // "Mar 23, 2017, 00:14 AM\n"
}
How to get the current time as datetime
Update for Swift 3:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
I do this:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
See the same question in objective-c How do I get hour and minutes from NSDate?
Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
How to display Yesterday, Today, and Tomorrow with DateFormatter
You need doesRelativeDateFormatting
(and don't forget to add styles), for eg:
var dateFormatter: DateFormatter {
let df = DateFormatter()
df.dateFormat = "MMM d, h:mm a"
df.dateStyle = .medium
df.timeStyle = .short
df.doesRelativeDateFormatting = true
return df
}
swift check date is today or tomorrow
You can use Calendar.current.ordinality
to compare the day of the year for the various dates. Here's an example that generates dates from today and tomorrow and then filters them back into separate arrays:
let today = Date()
let todayInts = Array(0..<10).map { today.timeIntervalSince1970 + TimeInterval($0) }
print("Today:", todayInts,"\n")
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)!
let tomorrowInts = Array(0..<10).map { tomorrow.timeIntervalSince1970 + TimeInterval($0) }
print("Tomorrow:", tomorrowInts,"\n")
let allInts = todayInts + tomorrowInts
let todayDayOfYear = Calendar.current.ordinality(of: .day, in: .year, for: today)!
let filteredTodayInts = allInts.filter { Calendar.current.ordinality(of: .day, in: .year, for: Date(timeIntervalSince1970: $0)) == todayDayOfYear }
print("Filtered today:", filteredTodayInts,"\n")
let tomorrowDayOfYear = todayDayOfYear + 1
let filteredTomorrowInts = allInts.filter { Calendar.current.ordinality(of: .day, in: .year, for: Date(timeIntervalSince1970: $0)) == tomorrowDayOfYear }
print("Filtered tomorrow:", filteredTomorrowInts,"\n")
Swift - Get next date
Here is the code snippet that may help you.
//Call method like this
convertNextDate(dateString: "31 12 2016")
// Method is here
func convertNextDate(dateString : String){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM yyyy"
let myDate = dateFormatter.date(from: dateString)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
let somedateString = dateFormatter.string(from: tomorrow!)
print("your next Date is \(somedateString)")
}
Another way is to create extension and here it is.
extension String {
func convertToNextDate(dateFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let myDate = dateFormatter.date(from: self)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
return dateFormatter.string(from: tomorrow!)
}
}
Usage
print("31 12 2016".convertToNextDate(dateFormat: "dd MM yyyy"))
Note: You can use use your desired date-format just make sure it is appropriate.
Related Topics
How to Run a Task in Swift on a Particular Date-Time in Background Either Application Is on or Off
@Ibdesignable - View Not Rendering as Expected
Change Title of a Navigation Bar Button Item
How to Set Cmutablepointer<Objcbool> to False in Swift
Ios10, Swift 3, and Fcm Delegate Error
Firebase Dynamic Link Doesnt Work in Safari Swift
Xcode 6 Project Crashing After Segue on iOS 7.1
Moya/Alamofire - Url Encoded Params with Same Keys
How to Trigger an API Call Before Displaying Local Notifications
Uiview Rounded Corner - Swift 2.0
Navigation with Only Back Button and Transparent Background
How to Get User Data from Facebook Sdk on iOS
How to Handle Homophones in Speech Recognition
How to Draw Text in Center to Uiimage
How to Convert Date (Without Knowing the Kind) to String