Swift: How to get string values of days, months and year from a date picker?
You have 2 ways to do that, depends if you want to see the number of the current month or his name:
- Use Calendar
- Use DateFormatter
With Calendar:
let calendar = Calendar.current
let components = calendar.dateComponents([.day,.month,.year], from: self.datePicker.date))
if let day = components.day, let month = components.month, let year = components.year {
let dayString = String(day)
let monthString = String(month)
let yearString = String(year)
}
With DateFormatter:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy"
let year: String = dateFormatter.string(from: self.datePicker.date))
dateFormatter.dateFormat = "MM"
let month: String = dateFormatter.string(from: self.datePicker.date))
dateFormatter.dateFormat = "dd"
let day: String = dateFormatter.string(from: self.datePicker.date))
With DateFormatter you have more choice of formatting because your manage the output format
Swift - Getting Date from Month, Day, Year Components
You cannot call date(from
on the type. You have to use an instance of the calendar, either the current
calendar
Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 15))
or a fixed one
let calendar = Calendar(identifier: .gregorian)
calendar.date(from: DateComponents(year: 2018, month: 1, day: 15))
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 reformat a Date to only Year Month and Day? Swift
Simply create a String
extension and
1. convert String
to Date
with format yyyy-MM-dd HH:mm:ssZZZZ
2. convert Date
to String
with format yyyy-MM-dd
extension String {
var formattedDate: String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZ"
if let date = dateFormatter.date(from: self) {
print(date)
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: date)
}
return nil
}
}
Example:
let dateStr = "2017-04-10 10:33:42GMT"
let formattedDate = dateStr.formattedDate //Output: "2017-04-10"
Get day of week using NSDate
What you are looking for (if I understand the question correctly) is NSCalendarUnit.CalendarUnitWeekday
. The corresponding property of NSDateComponents
is weekday
.
Note also that your date format is wrong (the
full specification can be found here: http://unicode.org/reports/tr35/tr35-6.html).
The function can be simplified slightly, using automatic type inference, also you use variables a lot where constants are sufficient.
In addition, the function should return an optional which is nil
for an invalid input string.
Updated code for Swift 3 and later:
func getDayOfWeek(_ today:String) -> Int? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
guard let todayDate = formatter.date(from: today) else { return nil }
let myCalendar = Calendar(identifier: .gregorian)
let weekDay = myCalendar.component(.weekday, from: todayDate)
return weekDay
}
Example:
if let weekday = getDayOfWeek("2014-08-27") {
print(weekday)
} else {
print("bad input")
}
Original answer for Swift 2:
func getDayOfWeek(today:String)->Int? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
if let todayDate = formatter.dateFromString(today) {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
let weekDay = myComponents.weekday
return weekDay
} else {
return nil
}
}
How to format date with DateFormatter that includes friendly day and month
Use EEEE
for the full weekday name and MMMM
for the full month name. But since you are parsing fixed formatted strings that are in English, you must also set the formatter's locale to en_US_POSIX
.
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, MMMM d, yyyy"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter.date(from: "Thursday, June 14, 2018")
Note that this will treat the date as being in the user's local timezone.
See the full specification for all possible date formatting patterns.
Related Topics
How to Hide the Navigation Back Button in Swiftui
Scenekit - Scntext Centering Incorrectly
Weak VS Unowned in Swift. What Are the Internal Differences
Swift Realm, Load the Pre-Populated Database the Right Way
Convert Float Value to String in Swift
When Should I Use Optionals and When Should I Use Non-Optionals with Default Values
How to Create a Noop Block for a Switch Case in Swift
Why Do I Still Need to Unwrap Swift Dictionary Value
How to Edit the Uiblureffect Intensity
Using "If Let" with Logical "Or" Operator
Dyld: Library Not Loaded: @Rpath/Libswiftcore.Dylib Problem with New Xcode (10.2)
Swiftui .Rotationeffect() Framing and Offsetting
Uitableview - Multiple Selection and Single Selection
Not Condition in 'If Case' Statement
How to Succinctly Get the First 5 Characters of a String in Swift
Asyncdetached Falling Back into Main Thread After Mainactor Call