String did not Convert Properly to Date in ios Swift - ios

I want to convert string to date everything is fine but still, it gives me an incorrect date according to string.
Code:
import UIKit
public class Utils {
public class func converServerTimeStampToDate (_ timeStamp: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy, hh:mm:ss a"
return dateFormatter.date(from: timeStamp)!
}
}
print(Utils.converServerTimeStampToDate("12/06/2017, 06:48:03 am"
))
-----OutPut-----
2017-12-06 14:48:03 +0000

To solve this problem set timezone
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
By default it is taking current time zone that's why your output is different from input.

It is correct result. When you convert any string into Date it will convert it in UTC timezone. And when you convert that date into string again it will be in your current timezone. So, convert that date into string and you real date you will get. So, your Date object always be in UTC timezone and your string will be always in your local timezone. And when you displays your date in label or any other control then definitely you will display in string format and it will be in your local timezone. So, there is nothing wrong in it. You just required to understand the concept!

Related

DateTime2 formart conversion to Swift Date

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.

Swift: Date parsing on daylight saving time

I have received date-time as String from server. I am unable to parse Date if date time is exact time of daylight saving time happen. How to handle when date-time string is "2022-03-13T02:00:00.000000"
Output:
2022-03-13 05:00:00 +0000
2022-03-13 06:59:00 +0000
failed
2022-03-13 07:00:00 +0000
2022-03-13 08:00:00 +0000
Code:
extension String {
func date(using format: String) {
let df = DateFormatter()
df.dateFormat = format
df.timeZone = .current
if let date = df.date(from: self) {
print(date)
}
else {
print("failed")
}
}
}
"2022-03-13T00:00:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
"2022-03-13T01:59:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
"2022-03-13T02:00:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
"2022-03-13T03:00:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
"2022-03-13T04:00:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
You just need to set your date formatter's calendar property. This will also avoid using the user device's calendar which might result in parsing the wrong year. Don't forget to always set your date formatter's locale to "en_US_POSIX" when parsing a fixed date format:
extension String {
func date(using format: String) -> Date? {
let df = DateFormatter()
df.calendar = .init(identifier: .iso8601)
df.locale = .init(identifier: "en_US_POSIX")
df.timeZone = .current
df.dateFormat = format
df.date(from: self)
}
}
Note also that this approach will create a new date formatter every time you call this method. You should avoid that as well creating a static formatter. I would also make sure if the date string is using the current timezone. Usually it is UTC timezone.
Adopt the ISO8601DateFormatter To convert those strings into dates, then when you need to display them into your app use a date formatter set to the desired time zone.
In this way you won’t have any trouble with daylight savings conversions.
Of course when you need to re-encode a date into a String For transmitting it use again the ISO8601DateFormatter In order to keep the same format used for receiving them.

How to get only time from date in swift

This question is not asked for the first time, but no solution works for me. I am getting time in String from Api response in the following format "14:45".
I want to compare this time with the current time, for this purpose I need to convert this string in Time formate(swift sports)
I always get nil after conversion
I have tried multiple ways but none of them worked for me and one is given for reference, I don't know what am I missing here
Thanks for any response
func stringToTime(str:String) -> Date{ // 14:45 passed here in str
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
print(str)
//here time string prints
let date = dateFormatter.date(from: (str))
print(date)
//date is nil here, should be 02:45 pm
return date!
}
If the time you get from the API is in 24h format you can do a string comparison
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
let currentTime = formatter.string(from: Date())
let compare = currentTime.compare("14:45")
You might need to set the time zone for the DateFormatter to make sure it uses the same as the API
It seems like you want to transform a time string in one format to another format. Your method signature should look like this:
func changeFormat(str:String) -> String {
Note that you should not output a Date here, because Dates don't have formats. They will always be printed in the same way. What you need to do in this method is 2 things:
parse str to a Date using a DateFormatter, specifying the format HH:mm. You seem to assume that DateFormatter can automatically work this format out. It can't :(
format the Date object you just got using a DateFormatter, specifying the format hh:mm a. This produces a string, not a date.
(You could also consider having the method return a Date (then it would be called parseTime), and do the second step just before you show the date to the screen.)
func changeFormat(str:String) -> String {
let dateFormatter = DateFormatter()
// step 1
dateFormatter.dateFormat = "HH:mm" // input format
let date = dateFormatter.date(from: str)!
// step 2
dateFormatter.dateFormat = "hh:mm a" // output format
let string = dateFormatter.string(from: date)
return string
}

String to date with UTC timezone

I am struggling with Date and I'm assuming is TimeZone.
Currently I get from my backend a string like this "2020-04-07" and when I try to convert it to date it turns into 2020-04-06 22:00:00 +0000. I am in Spain (UTC+2) which I guess this is why it removes 2 hours?
This is my date formatter:
var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone.current
return dateFormatter
}()
And I call it dateFormatter.date(from: startDateString)
I am setting my current timezone but seems to be ignoring it or am I missing something?
I have followed a lot of answers from here but it's always the same result.
Thank you
The Date object does not have any inherent locale / time zone. It just represents a moment in time. If you want to see that Date as a string in a specific locale/time zone you have to use a date formatter. Or there's descriptionWithLocale. If you use print it will print a debug description of the Date instance in UTC.

Bad converting String to NSDate

I have a problem with converting String to NSDate. In my text field when user tap on it, is a possibility to chose a date using UIDatePicker. String as a date in TextField looks like that: "yyyy-mm-dd" Now when I try to convert date for example on 2016-05-13 using this method:
func changeStringToNSDate(){
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
let from = moreSorts.fromDatePickerTextField.text!
let fromDate = dateFormatter.dateFromString(from)
print(fromDate)
}
When I print fromDateI recieve an information that fromDate is not 2016-05-13 but 2016-01-11 23:58:00 +0000. I don't know why I have 2016-01-11 when in my TextField String shows 2016-05-13
It's difficult to tell what might be going wrong for sure with the information you've provided. In a Swift playground I'm getting 2016-01-13 and not 2016-01-11, but if I change the date format, I can get 2016-05-13:
dateFormatter.dateFormat = "yyyy-MM-dd"
The uppercase MM is key. I would check out this website to play around with the date format options:
http://nsdateformatter.com

Resources