Convert time string into date swift
Always remember this: Date
/ NSDate
stores times in UTC. If your timezone is anything but UTC, the value returned by print(date)
will always be different.
You can make it print out the hour as stored in Firebase by specifying a UTC timezone. The default is the user's (i.e. your) timezone:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let item = "7:00 PM"
let date = dateFormatter.date(from: item)
print("Start: \(date)") // Start: Optional(2000-01-01 19:00:00 +0000)
Convert string to date in Swift
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)Finally create a new
Date
object and strip minutes and secondslet finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 10.12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
Convert string time into date swift
You can create an extension for string that returns a full date object by passing only the time string as follows.
extension String {
func createDateObjectWithTime(format: String = "HH:mm") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
guard let dateObjectWithTime = dateFormatter.date(from: self) else { return nil }
let gregorian = Calendar(identifier: .gregorian)
let now = Date()
let components: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]
var dateComponents = gregorian.dateComponents(components, from: now)
let calendar = Calendar.current
dateComponents.hour = calendar.component(.hour, from: dateObjectWithTime)
dateComponents.minute = calendar.component(.minute, from: dateObjectWithTime)
dateComponents.second = 0
return gregorian.date(from: dateComponents)
}
}
You can call the extension by:
let date = "15:26".createDateObjectWithTime()
How can I convert string date to NSDate?
try this:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.dateFromString(/* your_date_string */)
For further query, check NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.
Swift 3 and later (Swift 4 included)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
* http://userguide.icu-project.org/formatparse/datetime
*/
guard let date = dateFormatter.date(from: /* your_date_string */) else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}
// use date constant here
How to convert string to date without change time swift
You can add a timezone to dateFormatter
dateFromat.timeZone = TimeZone(secondsFromGMT: 0)
Updated code:
let scheduleDate : String = "2020-01-25 20:11:00"
let dateFromat : DateFormatter = DateFormatter()
dateFromat.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFromat.timeZone = TimeZone.init(secondsFromGMT: 0)
let dateFromString = dateFromat.date(from: scheduleDate)
print(dateFromString as Any)
Convert string containing date to Date
In addition to the Date being shown as an Optional, your format string appears to be wrong. "YYYY" should be "yyyy", so the whole line that assigns the formatter should be:
dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"
That change yields the output
"Optional(2022-01-18 16:39:00 +0000)"
In addition, you should really force the calendar to Gregorian or iso8601, and set its locale to "en_US_POSIX
:
An improved version of the date formatter could would look like this:
(from Leo's edit.)
let str = "Jan 18, 2022 04:39PM GMT"
let dateFormatter = DateFormatter()
dateFormatter.calendar = .init(identifier: .iso8601)
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "MMM d, yyyy hh:mma z"
if let date = dateFormatter.date(from: str) {
let dateString = dateFormatter.string(from: date)
print(dateString == str) // true
}
Related Topics
Missing Required Module Firebase - Jenkins Build Error
Close UIdatepicker After Selection When Style Is .Compact
Difference Between Firinstanceid.Instanceid().Token() and Messaging.Messaging().Fcmtoken
Type 'Bundle' Has No Member "Module"
How to Create a Pulse Effect on an Skspritenode
Negative Arrayslice: Index Is Out of Range
Perform Segue After UIalertcontroller Is Dismissed
Accessing an Actor's Isolated State from Within a Swiftui View
How to Initialize a Struct with a Closure Parameter Like This
Swift Playground with Debugger Support
Loading Image from Assets to Nsimage Keep Getting Error, Expecting Nsimage.Name
How to Get .Adjustsfontsizetofitwidth to Function Properly
Filtering Realm Objects with Swift
Swift Increment Int! Not Working
Crash Casting Wknsurlrequest As? Other Type
How to Use Passed Parameters in Swift Setmethodcallhandler - Self.Methodname(Result: Result)