incorrect string to date conversion swift 3.0
Your date string does not specify a year, which is therefore
determined from the default date. What you can do is to set the
default date to the (start of the) current day:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd hh:mm aa"
dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
if let dateCompleted = dateFormatter.date(from: "10/24 12:00 PM") {
print(dateCompleted) // 2017-10-24 10:00:00 +0000
}
(I am in the Europe/Berlin timezone, therefore 12:00 PM is printed
as 10:00 GMT.)
Swift convert string to date output wrong date
You need to understand that Date
does not only represent a date, but also a time.
>=
compares both date and time components of a Date
object. Since you didn't specified any time in your date string, the API assumed it to be 00:00:00 in your local time, which is 18:30:00 of the previous day in UTC. Why UTC, you ask? That's what the description
of the date always is. When you print a date, it always prints it in UTC time. To print it in your time zone, set the timeZone
property of your date formatter and format it.
One way to only compare the date components is by removing the time components. From this answer, this is how you remove time components:
public func removeTimeStamp(fromDate: Date) -> Date {
guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: fromDate)) else {
fatalError("Failed to strip time from Date object")
}
return date
}
Now this should be true:
dateStartDate >= removeTimeStamp(fromDate: dateToday)
dateFromString() returning wrong date swift 3.0
The format of date should be dd/MM/yyyy
not dd/mm/yyyy
. The mm
indicates the minutes and MM
indicates the month.
And also add the below line in your code
formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
This line of code set time zone. If you not, then you get 30/11/2017
in output.
The reason behind this is when string date not contain time then formatter assume that it is midnight and you also not given the timezone so it will take current timezone.
swift 3 - can not convert string to date
If your are pretty sure that buffers["pubDate"]!
is equal to "Sun, 02 Apr 2017 19:31:18 GMT" (or any date with the same format), then it should be:
var dateBuffer: Date {
let formatter = DateFormatter()
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
let date = formatter.date(from: buffers["pubDate"]!)
return date!
}
Note that the difference is HH:mm:ss
instead of hh:mm:ss
. For reading the hours as 24-clock convention, you should use HH
.
Also, to be more safe -from any unexpected crash-, I'd suggest to do some optional binding, as follows:
var dateBuffer: Date? {
let formatter = DateFormatter()
let str:String? = "Sun, 02 Apr 2017 19:31:18 GMT"
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
if let pubDate = buffers["pubDate"], let date = formatter.date(from: pubDate) {
return date
}
return nil
}
if let myDate = dateBuffer {
print(myDate)
}
Getting wrong date when converting string with timezone
// This lets us parse a date from the server using the RFC3339 format
let rfc3339DateFormatter = DateFormatter()
rfc3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
rfc3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
rfc3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
// This string is just a human readable format.
// The timezone at the end of this string does not mean your date
// will magically contain this timezone.
// It just tells the parser what timezone to use to convert this
// string into a date which is basically just seconds since epoch.
let string = "2019-01-14T00:00:00+08:00"
// At this point the date object has no timezone
let shiftDate = rfc3339DateFormatter.date(from: string)!
// If you want to keep printing in SGT, you have to give the formatter an SGT timezone.
let printFormatter = DateFormatter()
printFormatter.dateStyle = .none
printFormatter.timeStyle = .full
printFormatter.timeZone = TimeZone(abbreviation: "SGT")!
let formattedDate = printFormatter.string(from: shiftDate)
You will notice that it prints 12am. There is nothing wrong with your code. You just misunderstand the Date object. Most people do.
Edit: I used the RFC formatter found in the Apple docs here. The result is the same if you use your formatter. And yes, as rmatty said, there are a few things wrong with your formatter (I stand corrected :))
Swift - iOS - Convert String to Date & issue
Your DateFormatter's dateFormat should be "MMM d, yyyy hh:mm:ss a"
("yyyy" instead of "YYYY" and "hh" instead of "HH")
That works.
Edit:
Or, as Leo pointed out in the comments, "MMM d, yyyy h:mm:ss a"
(With only one h
) would be better, and it's safer to use
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
(That tells the date formatter not to try to adjust the date format for different local date formatting conventions.)
How to convert string to date correctly?
I will say more - it also works unexpectedly
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let dotDate = dateFormatter.date(from: "2020....07...10") // Optional(2020-07-09 21:00:00 +0000)
let commaDate = dateFormatter.date(from: "2020,,,,07,,,,10") // Optional(2020-07-09 21:00:00 +0000)
My version is probably the issue in internal implementation on Apple side and comparison with the ASCII code table, where the codes of these characters (,
,-
,.
,/
) are in order (from 44 to 47)
Related Topics
Retrieve Multiple Photos Under a Node from Firebase Storage
Making Parts of Text Bold in Swiftui
Why Do Integers Not Conform to the Anyobject Protocol
Add Constraints to Generic Parameters in Extension
Print the Nstableview's Row Number of the Row Clicked by the User
Open a Filedialog in Swiftui on MACos
How to Increase (Animate) the Width of the Square on Both Ends
Xcode 11 Beta 3, Build Error "Unknown Attribute 'State'", "Use of Undeclared Type 'View'" etc
Use of Undeclared Type 'Attributedstring'
Swift 2.0 'Inout' Function Parameters and Computed Properties
What Makes a Property a Computed Property in Swift
How to Embed Third Party Framework on Ionic Capacitor Custom Plugin
How to Generate Random Numbers Without Repetition in Swift
How to Get Iobluetoothdevice's Battery Level, Using Swift and Appkit (Xcode for MACos)