How do I convert this, "2021-07-05T22:26:51.159Z" to Date() with swift [duplicate] - ios

This question already has an answer here:
Swift ISO8601 format to Date returning fatal error
(1 answer)
Closed 1 year ago.
I think this is an ISO8601 formatted timestamp.
2021-07-05T22:26:51.159Z
I'm trying to convert it with ISO8601DateFormatter() in swift 5.
Here's what I've tried:
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = .withFullDate
//ISO8601DateFormatter().formatOptions = .withFractionalSeconds
let d = "2021-07-05T22:26:51.159Z"
let date = dateFormatter.date(from: d)
The result:
date = 2021-07-05 00:00:00 UTC
The day is correct, the time is not. I've tried to set the .withFractionalSeconds option. Didn't help.
How should I convert this format?

You can use standard date formatter to achieve this:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let date = dateFormatter.date(from: d)
print(date)

Related

Wrong date in swift 5 after conversion [duplicate]

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
}

Swift `yyyy-MM-dd'T'HH:mm:ss.sssZ` string to date [duplicate]

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'm formatting a date string to date object using below code. But for some date strings it works and for some it returns nil.
Format = "yyyy-MM-dd'T'HH:mm:ss.sssZ"
"2019-04-02T09:47:24.055Z" Works
"2019-03-27T22:31:17.140Z" Doesn't work
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ"
let date = dateFormatter.date(from: "2019-03-27T22:31:17.140Z")
Your format is wrong. It should be:
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Have a look at date time format here:
https://unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: "2019-04-02T09:47:24.055Z")
let date1 = dateFormatter.date(from: "2019-03-27T22:31:17.140Z")
print(">>>>>!!", date, date1)
Optional(2019-04-02 09:47:24 +0000) Optional(2019-03-27 22:31:17 +0000)
The code above works as expected.
use SSS instead of sss
for your case of
yyyy-MM-dd'T'HH:mm:ss.sssZ and 2019-04-02T09:47:24.055Z
output was :
Optional(2019-04-02 09:47:55 +0000) nil
look at minutes and seconds:)

dateFormatter returns wrong date with two digit year specifier [duplicate]

For date Input "00/02/02"
formating Style is yy/MM/dd
I am getting correct output like 02/01/2000
But issue is when trying with "00/01/01"
getting output like this '01/01/12100'
But I don't know why this year coming like 12100
My code is
let str = "00/01/01"
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "yy/MM/dd"
if let showDate = inputFormatter.date(from: str) {
inputFormatter.dateFormat = "dd/MM/yyyy"
let resultString = inputFormatter.string(from: showDate)
print(resultString)
}
year input type always as yy format.
As per the #MartinR suggestion
settinginputFormatter.defaultDate to current date or Date(timeIntervalSinceReferenceDate: 0) its worked fine
let str = "00/01/01"
let inputFormatter = DateFormatter()
inputFormatter.defaultDate = Date(timeIntervalSinceReferenceDate: 0)
inputFormatter.dateFormat = "yy/MM/dd"
if let showDate = inputFormatter.date(from: str) {
inputFormatter.dateFormat = "dd/MM/yyyy"
let resultString = inputFormatter.string(from: showDate)
print(resultString)
}
I managed to reproduce this bug by setting the timezone of the formatter, before getting the date from it, to your local timezone:
inputFormatter.timeZone = TimeZone(identifier: "Asia/Kolkata")
//Or
inputFormatter.timeZone = TimeZone(identifier: "Asia/Calcutta")
They both lead to 01/01/12100.
Actually, using a date format of yy/MM/dd hh:mm:ss, all dates starting from 00/01/01 00:00:00 to 00/01/01 05:29:59 give a year component of 12100. This is due to the time zone of Kolkata being offset by +05H30 from GMT. This is a bug.
Setting the timezone to UTC yields the desired output:
inputFormatter.timeZone = TimeZone(identifier: "UTC") //01/01/2000
This bug occurs with other timezones too:
inputFormatter.timeZone = TimeZone(identifier: "Africa/Addis_Ababa")
inputFormatter.timeZone = TimeZone(identifier: "Europe/Moscow")
inputFormatter.timeZone = TimeZone(identifier: "Asia/Hong_Kong")
Basically all timezones that have GMT + hh:mm

swift NSDate AM and Pm Format [duplicate]

This question already has answers here:
NSDateFormatter- stringFromDate not returning AM/PM
(6 answers)
Closed 5 years ago.
To convert date and time, I have used this:
let formatter = NSDateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.dateFormat = "M/dd/yyyy, h:mm"
formatter.AMSymbol = "AM"
formatter.PMSymbol = "PM"
let dateString = formatter.stringFromDate(model.courseDate)
print(dateString)
If the course date is "courseDate = "2017-01-09 01:00:00 +0000";"
but I am getting like this in print:
1/09/2017, 1:00 with no any AM or PM.
How can I achieve this?
Thanks.
according to the date formatter specs
You can retrieve a date in 24h format instead of requesting AM/PM by using
HH instead of hh
so the date "21/11/2016 01:30" (pm) would be "21/11/2016 13:30".
if you do need to print the format, though, you can print it using:
a
More date fomatting details here
As per Apple general date formatter you should use "M/dd/yyyy, hh:mm a" in your date format.
like : formatter.dateFormat = "M/dd/yyyy, hh:mm a"
Hope this will help you!
use following code may help full for you
//Call function
let dateTime = self.convertDateFormaterAamer(sendTimeStep, inputDateFormate: "dd-MM-yyyy HH:mm:ss", outputDateFormate: "dd-MMM-yyyy hh:mm a")
//Date function
func convertDateFormater(date: String,inputDateFormate: String , outputDateFormate: String) -> String
{
let dateFormatter = NSDateFormatter()
//dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
//dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = inputDateFormate
let date = dateFormatter.dateFromString(date)
//dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"
//dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = outputDateFormate
var timeStamp = ""
if (date != nil)
{
timeStamp = dateFormatter.stringFromDate(date!)
}
return timeStamp
}

How to convert milliseconds to date string in swift 3 [duplicate]

This question already has answers here:
NSDate timeIntervalSince1970 not working in Swift? [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to convert milliseconds to date string in swift 3,i tried by setting date fomatter but i am not getting current date string.
var milliseconds=1477593000000
let date = NSDate(timeIntervalSince1970: TimeInterval(milliseconds))
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
print(formatter.string(from: date as Date))
output:
22-01-48793 01:30:00
Try this,
var date = Date(timeIntervalSince1970: (1477593000000 / 1000.0))
print("date - \(date)")
You will get output as date :
date - 2016-10-27 18:30:00 +0000
How about trying this -
let milisecond = 1479714427
let dateVar = Date.init(timeIntervalSinceNow: TimeInterval(milisecond)/1000)
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm"
print(dateFormatter.string(from: dateVar))
Have a look at the documentation of NSDate:
convenience init(timeIntervalSince1970 secs: TimeInterval)
Returns an NSDate object initialized relative to the current date and time by a given number of seconds.
Just convert your milliseconds to seconds and you should get the correct date.

Resources