This question already has answers here:
How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?
(13 answers)
Closed 5 months ago.
I have a date as String but I want to convert it to Date.
The date in string looks like this - "2022-09-09T07:00:00.0000000".
Code to convert it to Date:
public static func dateStringToDate(dateString: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent
dateFormatter.timeZone = TimeZone.current
dateFormatter.setLocalizedDateFormatFromTemplate("MM-dd-yyyy HH:mm:ss")
return dateFormatter.date(from: dateString)
}
No matter what I do, I keep getting nil as the output. I tried with ISO8601 template as well and got nil. I commented out line "setLocalizedDateFormatFromTemplate" but still got nil. Can't figure out what am I missing or doing wrong in the code.
First of all, this is an excellent resource. I think what you are looking for is this:
func dateStringToDate(dateString: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS"
return dateFormatter.date(from: dateString)
}
dateStringToDate(dateString: "2022-09-09T07:00:00.0000000")
Sep 9, 2022 at 7:00 AM
You have the year, then month, then day, then hour, minute, second, fractional seconds
Use this Snippet of code
func dateStringToDate(dateString: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.autoupdatingCurrent
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
return dateFormatter.date(from: dateString)
}
You were not providing the proper date format
Related
I have a date string coming from back-end as "2022-08-16T13:44:11.8743234". Date formatting and conversion is the oldest skill in the book but I cannot figure out why I'm unable to convert that string to a Date object in Swift iOS. I just get nil with any source format I specify.
private func StringToDate(dateString: String) -> Date?
{
let formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-DDTHH:mm:ss.[nnnnnnn]"
let date = formatter.date(from: dateString)
return date //this is nil every time
}
DateTime2 is a more precise SQL Server extension of the normal C# DateTime, hence why the date string has 7 decimal places afters the seconds.
What am I doing wrong?
In your code the way you are handling the millisecond part is wrong. We use usually .SSS for milliseconds. Take a look at here it shows all the symbols related to date format.
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.date(from: "2022-08-16T13:44:11.8743234")
print(date)
In addition to that you are using DD for day. DD means the day of the year(numeric). So it should be dd. Same case is applied for the year as well.
This question already has answers here:
How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?
(13 answers)
Closed 3 years ago.
I am converting current date into GMT/UTC date string. But every time it returns me with wrong date.
My todays date is 07 February 2020, 11:09:20 AM. You can refer below image.
Here is my code :
let apiFormatter = DateFormatter()
//apiFormatter.dateStyle = DateFormatter.Style.long
//apiFormatter.timeStyle = DateFormatter.Style.long
//apiFormatter.calendar = Calendar.current
apiFormatter.timeZone = TimeZone.init(identifier: "GMT") //TimeZone(abbreviation: "UTC") //TimeZone.current //
//apiFormatter.locale = Locale.current
//apiFormatter.dateFormat = "yyyy-MM-DD HH:mm:ss"
apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
//apiFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ssZ"
let endDate = apiFormatter.string(from: Date())
print(endDate)
And what I am getting in return is also you can check in image - 2020-02-38T05:33:34.598Z. I have tried with all the format, but no any luck. Can anyone suggest where it is going wrong?
First of all, the format should be:
apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
The Z is not a literal letter, it's the description of the time zone. However, making it a literal won't probably make a problem.
The 38 for day from your output is obviously caused by the DD format you have commented out.
Nevertheless, you have to set the locale:
apiFormatter.locale = Locale(identifier: "en_US_POSIX")
Otherwise you will have problems with 12/24h switching.
let apiFormatter = DateFormatter()
apiFormatter.locale = Locale(identifier: "en_US_POSIX")
// remove this if you want to keep your current timezone (shouldn't really matter, the time is the same)
apiFormatter.timeZone = TimeZone(secondsFromGMT: 0)
apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let endDate = apiFormatter.string(from: Date())
print(endDate) // 2020-02-07T08:25:23.470+0000
print(Date()) // 2020-02-07 08:25:23 +0000
Also note that you can use ISO8601DateFormatter instead of DateFormatter.
Try this and adjust according to what format you are getting from server -
private func getFormatedDateInString(_ dateString: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
if let date = dateFormatter.date(from: dateString) {
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.timeZone = TimeZone.current
let timeStamp = dateFormatter.string(from: date)
return timeStamp
}
return nil
}
I'm using iPhone SE which contains iOS 12.2. I'm converting my date to following time format (h:MM a) which convert correct time but colon(:) between hour and minute removed.
My code as follows to convert time:
static func getDateInWithoutTimeZone(format: String, from timeStamp: Int64) -> String? {
let date = Date(timeIntervalSince1970: TimeInterval(timeStamp))
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = format //Specify your format that you want
return dateFormatter.string(from: date)
}
I'm using this method to convert time, where timestamp contain UNIX time value like 1555395758
I'm using above function as following:
guard let time = Date.getDateInWithoutTimeZone(format: "h:MM a", from: 1555395758) else {
return
}
And getting following output:
1104 AM
Am I doing anything wrong ? Or Is it issue with iOS 12.2?
Just change date format h:MM a to hh:mm a
Please refer below code.
static func getDateInWithoutTimeZone(format: String, from timeStamp: Int64) -> String? {
let date = Date(timeIntervalSince1970: TimeInterval(timeStamp))
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = format //Specify your format that you want
return dateFormatter.string(from: date)
}
guard let time = getDateInWithoutTimeZone(format: "hh:mm a", from: 1555395758) else {
return
}
print(time)
MM which stands for months, not minutes.
If you want to display hours and minutes (plus am/pm) your format string should be "h:mm a". Whenever you want to include charaters that are not directly format specifiers, it is recommended to include them in single quotes. So you could also use "h':'mm a". Note that the specifier you used in your example includes MM (capital M) which stands for months, not minutes.
i am passing "01/12/2017" in the fromDate.text(textfield), but receiving unexpected output.
let formatter = DateFormatter.init()
formatter.dateFormat = "dd/mm/yyyy"
startDate = formatter.date(from: fromDate.text!)
print("startDate = \(startDate)")
output is : 31/12/2016
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.
It has to be dd/MM/yyyy dateformat. MM in capital.
func convertToString(of dateTo: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy" //Your New Date format as per requirement change it own
let newDate: String = dateFormatter.string(from: dateTo) //pass Date here
print(newDate) //New formatted Date string
return newDate
}
I need to construct NSDate object from String, so I wrote the following code:
func getNSDateObjectFromString(string: String) -> NSDate {
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.dateFromString(string)
return date!
}
Unfortunately, the input string sometimes may contain milliseconds too. What can I do in this case? I don't find any way to read milliseconds (not in the day) according to the http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
Thanks in advance.
As far as I know, the format doesn't support "optional" fields. So you have to try the formats one by one:
func getNSDateObjectFromString(string: String) -> NSDate {
var formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
var date = formatter.dateFromString(string)
if date == nil {
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
date = formatter.dateFromString(string)
}
return date!
}
You can try something like:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
A Swift 3 Solution
After a bit of trial and error with the date format this is what worked for me with Swift 3.
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
let date = formatter.date(from: "2017-03-11 13:16:31.177")!
debugPrint(dateFormatter.string(from: date))
and after a round trip results in the expected debug output of
"2017-03-11 13:16:31.177"
Note that using the format "yyyy-MM-dd'T'HH:mm:ss.SSS" resulted in formatter.date(from: returning a nil optional Date.
Are they important?
In DateFormatter you create your matching string in years, months, days, hours, mins, secs, but you don't need to. If your matching string does not contain any of them, formatter will just ignore them.