Parsing JSON (Date) to Swift

How do I format JSON Date String with Swift?

Use the following string format to convert a server string into a Date

dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

Swift: parsing Date from JSON

You have a typo in your text:

print(object[0]["datareg"].dateTime)

should be

print(object[0]["datereg"].dateTime)

Parsing JSON (date) to Swift

That looks very similar to the JSON encoding for a date as used by Microsoft's ASP.NET AJAX, which
is described in An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET:

For example, Microsoft's ASP.NET AJAX uses neither of the described
conventions. Rather, it encodes .NET DateTime values as a JSON string,
where the content of the string is /Date(ticks)/ and where ticks
represents milliseconds since epoch (UTC). So November 29, 1989,
4:55:30 AM, in UTC is encoded as "\/Date(628318530718)\/".

The only difference is that you have the format /Date(ticks)/
and not \/Date(ticks)\/.

You have to extract the number between the parentheses. Dividing that by 1000
gives the number in seconds since 1 January 1970.

The following code shows how that could be done. It is implemented as
a "failable convenience initializer" for NSDate:

extension NSDate {
convenience init?(jsonDate: String) {

let prefix = "/Date("
let suffix = ")/"
// Check for correct format:
if jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) {
// Extract the number as a string:
let from = jsonDate.startIndex.advancedBy(prefix.characters.count)
let to = jsonDate.endIndex.advancedBy(-suffix.characters.count)
// Convert milliseconds to double
guard let milliSeconds = Double(jsonDate[from ..< to]) else {
return nil
}
// Create NSDate with this UNIX timestamp
self.init(timeIntervalSince1970: milliSeconds/1000.0)
} else {
return nil
}
}
}

Example usage (with your date string):

if let theDate = NSDate(jsonDate: "/Date(1420420409680)/") {
print(theDate)
} else {
print("wrong format")
}

This gives the output


2015-01-05 01:13:29 +0000

Update for Swift 3 (Xcode 8):

extension Date {
init?(jsonDate: String) {

let prefix = "/Date("
let suffix = ")/"

// Check for correct format:
guard jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) else { return nil }

// Extract the number as a string:
let from = jsonDate.index(jsonDate.startIndex, offsetBy: prefix.characters.count)
let to = jsonDate.index(jsonDate.endIndex, offsetBy: -suffix.characters.count)

// Convert milliseconds to double
guard let milliSeconds = Double(jsonDate[from ..< to]) else { return nil }

// Create NSDate with this UNIX timestamp
self.init(timeIntervalSince1970: milliSeconds/1000.0)
}
}

Example:

if let theDate = Date(jsonDate: "/Date(1420420409680)/") {
print(theDate)
} else {
print("wrong format")
}

Swift - Converting JSON date to Swift compatible date

The issue is that str and date2 two are not the same date format. str format is "yyyy-MM-dd'T'HH:mm:ssZ" while date2 format is "yyyy-MM-dd'T'HH:mm:ss.SSSZ". Besides that you should always set your dateFormatter's locale to "en_US_POSIX" when parsing fixed-format dates:

let date2 = "2015-05-15T21:58:00.066Z"

let dateFormatter = DateFormatter()
dateFormatter.locale = .init(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: date2) {
print(date) // "2015-05-15 21:58:00 +0000"
}

Parsing arbitrary format JSON date with Swift Decodable

First, follow the Swift naming convention: UpperCamelCase for class name and lowerCamelCase for variable name. Second, do yourself a favor and make created_at a Date field, like it's clearly is. That will save you a ton of headache later on.

Here's the code:

struct SiteData: Decodable{
let data: [Site]
}

struct Site: Decodable {
let id: Int
let url: String
let title: String
let created_at: Date // changed to Date
let sent: Bool
let alternative: String
let things: [String]
let description: [String]
let company: String
}

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let sites = try decoder.decode(SiteData.self, from: json)

Now that created_at has been parsed from JSON as a proper Date, you can format it however you like:

let formatter2 = DateFormatter()
formatter2.dateFormat = "MM-dd-yyyy"
print(formatter2.string(from: sites.data[0].created_at))

Note that DateFormatter is quite expensive to create and changing its dateFormat property is even more so. If you have to format a lot of dates to strings (or vice versa), create the date formatters only once and keep reusing them.

Convert JSON string into Date time and compare swift

You can use like:

 if let strResp = json["data"]{
let strDate = "\(strResp!)" //15:55
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm" // Pass any format here you want according to your date response
let convDate = dateFormatter.date(from: strDate)
print(convDate!)
}

Date Formatter Parse JSON date

You are using both style and dateFormat. Don't.

Either specify the style or – in this example – dateFormat. And set the locale to a fixed value.

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let articleDate = dateFormatter.date(from: sectionsNews.News!.created) ?? Date()

Side note:

Creating a string from a string ("\(sectionsNews.News!.created)") is redundant.

how to get datetime from json in swift 3

let dateString = dict["now_in"]!["date"]

will give you the date string. If you want Date object you can parse it using

let format = "yyyy-MM-dd'T'HH:mm:ss"
let formatter = DateFormatter()
formatter.dateFormat = format
let date = formatter.date(from: dateString)


Related Topics



Leave a reply



Submit