Wrong date in swift 5 after conversion [duplicate] - ios

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
}

Related

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

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)

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:)

why Date will return nil when using correct format in swift 4?

so here is the string Date that I want to Convert
2019-03-22T00:00:00
and here is the problem
Remember that I used "yyyy-MM-dd'T'HH:mm:ss" or "yyyy-MM-ddTHH:mm:ss" or "yyyy-MM-dd HH:mm:ss" or yyyy-MM-dd'T'HH:mm:ssZ and some other similar formats
You have to set a time zone and locale when parsing internet dates:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
// necessary to avoid daylight saving (and other time shift) problems
dateFormatter.timeZone = TimeZone(secondsFromGMT: TimeZone.current.secondsFromGMT())
// necessary to avoid problems with 12h vs 24h time formatting
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
print(dateFormatter.date(from: "2019-03-22T00:00:00"))
The default time zone contains information about daylight saving time and some specific times does not exist there. Instead, we have to use a generic time zone.
See https://developer.apple.com/library/archive/qa/qa1480/_index.html
22 March 2019 around midnight is the day & time when daylight saving change in Iran makes an hour non-existent.
The same can be achieved using ISO8601DateFormatter:
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = ISO8601DateFormatter.Options.withInternetDateTime.subtracting(.withTimeZone)
print(dateFormatter.date(from: "2019-03-22T00:00:00"))
Try this function might help
public func dateFormatter(strDate: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "fa_IR")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = dateFormatter.date(from: strDate)
let dateString = dateFormatter.string(from: date!)
return dateString
}
dateFormatter.isLenient = true
Ignores missing hours during daylight saving time offset

How to format a date using timezone in Swift?

I have checked other questions but none of them helped me much.
I have following string:
let dateString = "2018-04-29T21:00:00.000Z"
I have successfully converted it to date using the following:
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let convertedDate = dateFormatter.date(from: dateString)
But now I only want the time "hh:mm a" using timezone such as "+8". I have tried following way but it's not working:
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC+8")
dateFormatter.dateFormat = "hh:mm a"
let requiredTime = dateFormatter.string(from: convertedDate!)
Can anyone help me to overcome this problem?
The format you want is hh:mm a Z, which will provide the +0800.
You want to create a TimeZone which +8 hours from GMT, normally I prefer to use the appropriate abrivations (ie AET), but I guess if you don't have that, you can create a TimeZone using secondsFromGMT, for example...
let tz = TimeZone(secondsFromGMT: 8 * 60 * 60)
let toFormatter = DateFormatter()
toFormatter.timeZone = tz
toFormatter.dateFormat = "hh:mm a Z"
let requiredTime = toFormatter.string(from: convertedDate!)
Which based on your example data, will produce a value of...
05:00 AM +0800

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
}

Resources