Bad converting String to NSDate - ios

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

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.

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
}

Formatting JSON date to Swift date doesn't work

I'm trying to format this date: 2018-01-10T11:57:21.153 to Swift Date object like this:
let dateSentString = jsonDict["date"] as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from: dateSentString)!
For some reason, the app crashes on the last line.
What am I doing wrong? Thanks!
change the milli seconds format use 'SSS' specifier (with number of S's equal to number of digits of milliseconds ). for more information you get here
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
from
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
Full code
let dateSentString = "2018-01-10T11:57:21.153"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = dateFormatter.date(from: dateSentString)!
print(date)
You have to first set formatter for date you are getting from JSON and then another formatter for the date you want.
First convert string fro JSON to a date variable by setting same format coming in JSON object .
Then you have to re-format that date variable into format you want.
I can write code if you want but it is better to try yourself.
Happy Coding

String did not Convert Properly to Date in ios Swift

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!

Convert Specific Date String to Swift 3 Date While Adjusting for TimeZone

I know how to convert a datestring in this format (2016-11-02 05:45:05.000000) to a date in Swift3 but I can't figure out why the time that spits back out from the print command is off from the original by so much? From reading it might be setting it to a different timezone, but if that is the case how do I reset it back to the original time?
It incorrectly looks like this below for the sample time I gave above. Notice it's off by many hours.
2016-11-02 12:45:05 +0000
Here is my code below and the image showing the console print commands.
let dateString : String = task["created"]!.asDictionary!["date"]!.asString!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSSS"
let date = dateFormatter.date(from: dateString)
print(name)
print("\(id)")
print(desc)
print(dateString)
print(date!)
Please refer to the image.
You need to set the timezone:
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

Resources