Date Format in Swift
You have to declare 2 different NSDateFormatters
, the first to convert the string to a NSDate
and the second to print the date in your format.
Try this code:
let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))
Swift 3 and higher:
From Swift 3 NSDate
class has been changed to Date
and NSDateFormatter
to DateFormatter
.
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
print(dateFormatterPrint.string(from: date))
} else {
print("There was an error decoding the string")
}
Formatting a Date and Time in Swift
You can convert the String
to Date
and handle all operations that you would like to do with it.
- As the input format is not a standard one I assume that we are using UTC.
- If the input changes the function will throw an error without breaking most of your code.
enum DateFormattingErrors: Error {
case invalidFormat
}
func formatDate(_ from: String) throws -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
guard let date = dateFormatter.date(from: from) else {
throw DateFormattingErrors.invalidFormat
}
return date
}
func UTCFormattedDate(_ from: Date, withDate: Bool) -> String {
let utcDateFormatter = DateFormatter()
if withDate {
utcDateFormatter.dateStyle = .medium
}
utcDateFormatter.timeStyle = .medium
utcDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
return utcDateFormatter.string(from: from)
}
do {
let date = try formatDate("2022-01-09T19:04:16")
print(Date().description)
print(date.timeIntervalSinceNow) //Time difference between given date and current date
print(UTCFormattedDate(date, withDate: false)) // Better representation of date
} catch {
print(error)
}
Output
2022-01-10 10:09:03 +0000 //CurrentDate
-54287.22359800339 //Time difference current and given
7:04:16 PM //Formatted date
Swift date format returning wrong date
The code in your question is muddled up. You try to convert a string into a string in the first example and something unspecified into a Date
in the second example.
Here's how to convert a Date
into a String
:
import Foundation
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
let string: String = formatter.string(from: Date())
print(string) // prints for example 2020-10-18T10:54:07+01:00
Here's how to convert a string into a date
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ssZ"
let date: Date = formatter.date(from: "2020-10-18 10:59:56+0100")! // In real life, handle the optional properly
print(date) // prints 2020-10-18 09:59:56 +0000
When you print a Date directly, it automatically uses UTC as the time zone. This is why it changed it in the code above.
In the examples, I explicitly specified the type of string
and date
to show what type they are. Type inference means you can omit these in normal code.
As a general rule when handling dates:
- always use
Date
in your code.Date
is a type that stores the number of seconds since Jan 1st 1970 UTC. - Only convert dates to strings when displaying them to the user or communicating with an external system.
- When calculating periods etc, always use a Calendar to get things like date components and intervals in units other than seconds. You might think to get "the same time tomorrow" you could just add 24 * 60 * 60 to a
Date
but in many countries, like mine, that will work on only 363 days in the year.Calendar
will correctly handle things like daylight saving and leap years.
Getting different time formats on simulator and local devices - Swift iOS
Reason you are getting different result is because the locale of your mac (Simulator) and your iPhone are different and DateFormatter depends on locale to turn date into string. when you don't give DateFormatter explicit locale it uses your device, so if you need same result, set locale.
func today() -> String {
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.locale = Locale(identifier: "en_US")
return dateFormatter.string(from: date)
}
here's an interesting site to check different results.
https://nsdateformatter.com
Swift convert datetime format to another format
It crashes because your datestring format and the format in which you want to convert is different. Change the dateFormat to dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
Here is the code:-
let dateString = "2020-05-01 11:00 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateres = dateFormatter.date(from: dateString)
print(dateres)
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!
Related Topics
How to Add Headerview in Uicollectionview Like Uitableview's Tableheaderview
Change Order of Read Items with Voiceover
Cagradientlayer Diagonal Gradient
How to Change the Uisearchbar Search Text Color
How to Turn Flashlight on and Off in Swift
Uiscrollview Adjusts Contentoffset When Contentsize Changes
Number of Threads Created by Gcd
How to Custom Modal View Controller Presenting Animation
Creating a 3X3 Grid with Auto Layout Constraints
Detecting Active Avaudiosessions on iOS Device
iOS Tesseract Ocr Image Preperation
Xcode 8, iOS 10 - "Starting Webfilter Logging for Process"
How to Open Location Services Screen from Setting Screen
iOS 9 - "Attempt to Delete and Reload the Same Index Path"
Using Custom Fonts with Xcode 6/iOS 8 Interface Builder Launch Screen