How to convert a date string from Rails into Swift - ios

Please bear with me as I'm new to Swift: I'm writing a little app that calls an API (Rails) which return some data. The problem I'm having is that the date provided by the API comes like this: yyyy-MM-dd'T'HH:mm:sssZ my function expects yyyy-MM-dd'T'HH:mm:ssZ Please note the extra second
Here's my function:
public func dateFromString(date: String, format: String) -> NSDate {
if dateFormatter == nil {
dateFormatter = NSDateFormatter()
}
dateFormatter!.dateFormat = format
return dateFormatter!.dateFromString(date)!
}
On the console, when I try to run the app I get this:
date String "2015-04-13T12:48:23.310Z"
format String "yyyy-MM-dd'T'HH:mm:ssZ"
Any ideas on how I should resolve this?

You can do if you use the SSS as format string, like below.
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
See also: Date Format Patterns

You can use the following function:
func dateFromate(_ stringTime:String) -> String{
//"2015-04-13T12:48:23.310Z"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
guard let date2 = formatter.date(from: stringTime) else{
return stringTime
}
let date1 = Date()
return date1.offset(from: date2)
}

Related

How to convert a sting to a date, and back again, in swift?

I receive a timestamp from a JSON request, and I want to format it to a user-friendly format. Both the input, as the desired output are of type 'String'.
The format of the input timestamp is: 2020-03-07T12:18:26.347Z
Using the following code, I try to convert it to the desired format. But it will just output the value of Date(), indicating that the output of formatter.date(from: date) is nil.
What am I missing?
func convertDate(date: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "d-M-y, HH:mm"
let convertedDate = formatter.date(from: date) ?? Date()
return formatter.string(from: convertedDate)
}
Your dateFormat doesn't match the format of your input string. You want something like:
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
After struggling with it for hours, this answer, together with the date format information found here, I figured it out. I did previously not describe to the dateformatter how the input string would look.
func convertDate(date: String) -> String {
let dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
//`date(from:)` returns an optional so make sure you unwrap when using.
let dateFromString: Date? = dateFormatter.date(from: date)
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy, HH:mm"
//Using the dateFromString variable from before.
let stringDate: String = formatter.string(from: dateFromString!)
return stringDate
}

Swift how to convert date format [duplicate]

This question already has answers here:
Date Format in Swift
(24 answers)
Closed 2 years ago.
I have a date of type date and has a format "yyyy-MM-dd HH:mm:ss" and I would like to convert it to "yyyy-MM-dd". I am not sure how to achieve this since the date is of type Date.
Example :
let dateComponents: Date? = dateFormatterGet.date(from: "2019-03-11 17:01:26")
Required output :
Date object of format type "yyyy-MM-dd"
It is important to note that I have only date objects and no string.
You have a date of type String, not Date.
You use one DateFormatter to convert it to Date (check that the DateFormatter doesn't return nil).
Then you use another DateFormatter to convert the Date to a string.
Please don't use "dateComponents" as a variable name. You never, ever touch date components in your code. And you don't need to specify the type, just "let date = ..." or better "if let date = ..." checking for nil.
you can use like this:
let now = Date().UTCToLocalDateConvrt(format: "yyyy-MM-dd HH:mm:ss",convertedFormat : "yyyy-MM-dd")
put below function in Date extension class:
extension Date {
func UTCToLocalDateConvrt(format: String,convertedFormat: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let timeStamp = dateFormatter.string(from: self)
dateFormatter.dateFormat = convertedFormat
guard let date = dateFormatter.date(from: timeStamp)else{
return Date()
}
return date
}
}
func formatDate(yourDate: String) -> String { // "yyyy-MM-dd HH:mm:ss"
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss" // here you can change the format that enters the func
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd" // here you can change the format that exits the func
if let date = dateFormatterGet.date(from: yourDate) {
return dateFormatterPrint.string(from: date)
} else {
return nil
}
}
use it like this:
formatDate(yourDate: "2019-03-11 17:01:26")
it will return an optional string, that can be nil, make sure you are safety unwrap it (if let , guard let)
answer based on link

Using DateFormatter to parse this string into a Date?

I'm hitting a webservice that is returning a string in the following format:
"yyyy-MM-dd'T'HH:mmZ"
It's very close to the standard UTC format, but just without the ss at the end. My issue is that my dateFormatter is always returning nil...and I have tried to make sure that locale and everything else is setup properly.
Here is an example of an actual string:
2019-12-26T00:00Z
Here is the code that creates the DF:
extension DateFormatter {
#objc static func defaultDateFormat(_ format: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "US")
formatter.dateFormat = format
return formatter
}
func date(from string: String?) -> Date? {
if let string = string {
return self.date(from: string)
} else {
return nil
}
}
func string(fromOptional date: Date?) -> String? {
if let date = date {
return self.string(from: date)
} else {
return nil
}
}
func string(fromOptional date: Date?, defaultStr: String) -> String {
return self.string(fromOptional: date) ?? defaultStr
}
}
let df = DateFormatter.defaultDateFormat("yyyy-MM-dd'T'HH:mmZ")
let date: Date? = df.date(from: __dateString__) // always nil
A few observations:
You want to use a locale of en_US_POSIX, an invariant locale that always works for ISO 8601 / RFC 3339 date strings. See Technical Q&A 1480.
If you want to use this formatter to convert a date back to a string like 2019-12-26T00:00Z, you will want to:
Use X (or ZZZZZ or XXXXX) in your format string, not Z (see the “zone” section in the table at Date Format Patterns and you’ll see how these various time zone patterns, e.g. Z, ZZZZZ, and X, are interpreted); and
Set the timeZone of the formatter to use Zulu/GMT/UTC.
Thus:
#objc static func defaultDateFormat(_ format: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = format
return formatter
}
And
let df = DateFormatter.defaultDateFormat("yyyy-MM-dd'T'HH:mmX")
let date = df.date(from: "2019-12-26T00:00Z")
Or
let string = df.string(from: Date())

Not able to get date in string format

I'm storing some dates in coredata in Date format. In another viewcontroller, I want to retrieve those dates and convert them to string. I tried to achieve it like so...
if let bday = result.birthday {
print(bday)
let formatter = DateFormatter()
let bDateString = formatter.string(from: bday as Date)
print(bDateString)
self.birthdate = bDateString
}
Here, printing bday gives the proper date. But printing bDateString after converting to string gives nil. What am I doing wrong...?
Please provide format of date like this :
formatter.dateFormat = "MM-dd-yyyy" //provide your date format here
The issue is you have not provided date format.
Even you can use this extension
extension Date { static func getFormattedDate(string: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz" // This formate is input formated .
let formateDate = dateFormatter.date(from:"2018-02-02 06:50:16 +0000")!
dateFormatter.dateFormat = "dd-MM-yyyy" // Output Formated
print ("Print :\(dateFormatter.string(from: formateDate))")//Print :02-02-2018
return dateFormatter.string(from: formateDate)
} }

How to format date in Swift that similarly matches Json?

I am having trouble generating Date objects that match the json output. In http://chartapi.finance.yahoo.com/instrument/1.0/aapl/chartdata;type=quote;range=1y/json - the dates are in the following format "Date": 20151013. In order to get 2015-10-13, first I use Alamofire & SwiftJSON in my API call and JSON parsing. Here are some relevant lines from my code:
let dateInteger = subJson["Date"].int
if dateInteger != nil {
let editedDateInt = dateInteger!
let dateString = NSMutableString(string: "\(editedDateInt)")
dateString.insert("-", at: 4)
dateString.insert("-", at: 7)
chartpoint.date = Formatters.sharedInstance.dateFromString(key: dateString as String) }
// date extension
public class Formatters {
public static let sharedInstance = Formatters()
private let dateKeyFormatter = DateFormatter()
init() { dateKeyFormatter.dateFormat = "yyyy-MM-dd" }
public func dateFromString(key: String?) -> Date? {
guard let key = key else { return nil }
return dateKeyFormatter.date(from: key) }
Problem is the output came up Optional(2015-10-12 16:00:00 +0000). Not quite 2015-10-13 that I was expecting. How do I fix this? Is this related to user's Locale or TimeZone?
Check this out
Swift 3.0
let dateFromServer = "20151013"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
let date = dateFormatter.date(from: dateFromServer)
dateFormatter.dateFormat = "yyyy-MM-dd"
let finalDate = dateFormatter.string(from: date!)
print(finalDate)
Output:
2015-10-13
As suggested by #rmaddy changed the format style form YYYY to yyyy.

Resources