Converting UTC time in Swift
I'm trying to use an API in a practice project and one of the values in the JSON, dateTimeLocal
, is a date & time in UTC format.
In my cellForRowAt
method I put the date/time into a label:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "eventsCell", for: indexPath) as! EventsTableViewCell
let event = eventData[indexPath.row]
cell.eventTimeLabel.text = event.dateTimeLocal
return cell
}
And this prints out the date and time as:
2018-11-26T19:00:00
I'd like to get this date and time in a format that reads, using the above date/time as an example,
November 26, 2018 @ 7:00pm
Is this possible or will I have to include the date and time in the given UTC format?
Here's the rest of the code if it's applicable to this issue:
The structs to decode the JSON:
struct Welcome: Decodable {
let events: [Event]
}
struct Event: Decodable {
let title: String
let dateTimeLocal: String
let venue: Venue
enum CodingKeys: String, CodingKey {
case title
case dateTimeLocal = "datetime_local"
case venue
}
}
And this function to fetch the data:
func fetchData<T: Decodable>(url: URL, completion: @escaping (FetchResult<T>) -> (Void)) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {completion(.failure(error!)); return}
do {
let object = try JSONDecoder().decode(T.self, from: data)
completion(.success(object))
} catch {
completion(.failure(error))
}
}.resume()
}
Which is called in my viewDidLoad
:
fetchData(url: seatGeekApiUrl) { (result: FetchResult<Welcome>) -> (Void) in
switch result {
case .success(let object): self.eventData = object.events
print("neventData: nn(self.eventData)")
case .failure(let error):
print("nError decoding JSON: nn(error)")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
ios swift
add a comment |
I'm trying to use an API in a practice project and one of the values in the JSON, dateTimeLocal
, is a date & time in UTC format.
In my cellForRowAt
method I put the date/time into a label:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "eventsCell", for: indexPath) as! EventsTableViewCell
let event = eventData[indexPath.row]
cell.eventTimeLabel.text = event.dateTimeLocal
return cell
}
And this prints out the date and time as:
2018-11-26T19:00:00
I'd like to get this date and time in a format that reads, using the above date/time as an example,
November 26, 2018 @ 7:00pm
Is this possible or will I have to include the date and time in the given UTC format?
Here's the rest of the code if it's applicable to this issue:
The structs to decode the JSON:
struct Welcome: Decodable {
let events: [Event]
}
struct Event: Decodable {
let title: String
let dateTimeLocal: String
let venue: Venue
enum CodingKeys: String, CodingKey {
case title
case dateTimeLocal = "datetime_local"
case venue
}
}
And this function to fetch the data:
func fetchData<T: Decodable>(url: URL, completion: @escaping (FetchResult<T>) -> (Void)) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {completion(.failure(error!)); return}
do {
let object = try JSONDecoder().decode(T.self, from: data)
completion(.success(object))
} catch {
completion(.failure(error))
}
}.resume()
}
Which is called in my viewDidLoad
:
fetchData(url: seatGeekApiUrl) { (result: FetchResult<Welcome>) -> (Void) in
switch result {
case .success(let object): self.eventData = object.events
print("neventData: nn(self.eventData)")
case .failure(let error):
print("nError decoding JSON: nn(error)")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
ios swift
add a comment |
I'm trying to use an API in a practice project and one of the values in the JSON, dateTimeLocal
, is a date & time in UTC format.
In my cellForRowAt
method I put the date/time into a label:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "eventsCell", for: indexPath) as! EventsTableViewCell
let event = eventData[indexPath.row]
cell.eventTimeLabel.text = event.dateTimeLocal
return cell
}
And this prints out the date and time as:
2018-11-26T19:00:00
I'd like to get this date and time in a format that reads, using the above date/time as an example,
November 26, 2018 @ 7:00pm
Is this possible or will I have to include the date and time in the given UTC format?
Here's the rest of the code if it's applicable to this issue:
The structs to decode the JSON:
struct Welcome: Decodable {
let events: [Event]
}
struct Event: Decodable {
let title: String
let dateTimeLocal: String
let venue: Venue
enum CodingKeys: String, CodingKey {
case title
case dateTimeLocal = "datetime_local"
case venue
}
}
And this function to fetch the data:
func fetchData<T: Decodable>(url: URL, completion: @escaping (FetchResult<T>) -> (Void)) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {completion(.failure(error!)); return}
do {
let object = try JSONDecoder().decode(T.self, from: data)
completion(.success(object))
} catch {
completion(.failure(error))
}
}.resume()
}
Which is called in my viewDidLoad
:
fetchData(url: seatGeekApiUrl) { (result: FetchResult<Welcome>) -> (Void) in
switch result {
case .success(let object): self.eventData = object.events
print("neventData: nn(self.eventData)")
case .failure(let error):
print("nError decoding JSON: nn(error)")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
ios swift
I'm trying to use an API in a practice project and one of the values in the JSON, dateTimeLocal
, is a date & time in UTC format.
In my cellForRowAt
method I put the date/time into a label:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "eventsCell", for: indexPath) as! EventsTableViewCell
let event = eventData[indexPath.row]
cell.eventTimeLabel.text = event.dateTimeLocal
return cell
}
And this prints out the date and time as:
2018-11-26T19:00:00
I'd like to get this date and time in a format that reads, using the above date/time as an example,
November 26, 2018 @ 7:00pm
Is this possible or will I have to include the date and time in the given UTC format?
Here's the rest of the code if it's applicable to this issue:
The structs to decode the JSON:
struct Welcome: Decodable {
let events: [Event]
}
struct Event: Decodable {
let title: String
let dateTimeLocal: String
let venue: Venue
enum CodingKeys: String, CodingKey {
case title
case dateTimeLocal = "datetime_local"
case venue
}
}
And this function to fetch the data:
func fetchData<T: Decodable>(url: URL, completion: @escaping (FetchResult<T>) -> (Void)) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {completion(.failure(error!)); return}
do {
let object = try JSONDecoder().decode(T.self, from: data)
completion(.success(object))
} catch {
completion(.failure(error))
}
}.resume()
}
Which is called in my viewDidLoad
:
fetchData(url: seatGeekApiUrl) { (result: FetchResult<Welcome>) -> (Void) in
switch result {
case .success(let object): self.eventData = object.events
print("neventData: nn(self.eventData)")
case .failure(let error):
print("nError decoding JSON: nn(error)")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
ios swift
ios swift
asked Nov 25 '18 at 19:42
KingTimKingTim
5261821
5261821
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
First of all decode dateTimeLocal
as Date
let dateTimeLocal: Date
and add the appropriate date decoding strategy to decode the (not fully compliant) ISO 8601 string
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(formatter)
let object = try decoder.decode(T.self, from: data)
In the view controller class add a static date formatter on the top level
let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMMM dd, yyyy '@' h:mma"
return formatter
}()
and in cellForRow
assign the formatted date
cell.eventTimeLabel.text = dateFormatter.string(from: event.dateTimeLocal)
Thanks vadian you're a huge help as always - the date decoding strategy that you suggest will go in thedo
portion of thefetchData
function (thanks to you for help with that as well)? Or shall I make a separate function to handle the dates?
– KingTim
Nov 25 '18 at 20:06
Just replace the singledecode
line in thedo
block with the 3 lines
– vadian
Nov 25 '18 at 20:08
Got it - I'm getting an errordataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "datetime_local", intValue: nil)], debugDescription: "Expected date string to be ISO8601-formatted.", underlyingError: nil))
. I'm not changing anything in my call tofetchData
inviewDidLoad
am I?
– KingTim
Nov 25 '18 at 20:11
1
Darn, the string is not fully ISO8601 compliant (the trailing Z is missing). I updated the answer.
– vadian
Nov 25 '18 at 20:20
That did the trick! Thatformatter
is really useful! I'll have to look into ISO8601, I'm not familiar with that at all. Thanks a million vadian, hope you're having a great weekend.
– KingTim
Nov 25 '18 at 20:26
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471199%2fconverting-utc-time-in-swift%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
First of all decode dateTimeLocal
as Date
let dateTimeLocal: Date
and add the appropriate date decoding strategy to decode the (not fully compliant) ISO 8601 string
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(formatter)
let object = try decoder.decode(T.self, from: data)
In the view controller class add a static date formatter on the top level
let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMMM dd, yyyy '@' h:mma"
return formatter
}()
and in cellForRow
assign the formatted date
cell.eventTimeLabel.text = dateFormatter.string(from: event.dateTimeLocal)
Thanks vadian you're a huge help as always - the date decoding strategy that you suggest will go in thedo
portion of thefetchData
function (thanks to you for help with that as well)? Or shall I make a separate function to handle the dates?
– KingTim
Nov 25 '18 at 20:06
Just replace the singledecode
line in thedo
block with the 3 lines
– vadian
Nov 25 '18 at 20:08
Got it - I'm getting an errordataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "datetime_local", intValue: nil)], debugDescription: "Expected date string to be ISO8601-formatted.", underlyingError: nil))
. I'm not changing anything in my call tofetchData
inviewDidLoad
am I?
– KingTim
Nov 25 '18 at 20:11
1
Darn, the string is not fully ISO8601 compliant (the trailing Z is missing). I updated the answer.
– vadian
Nov 25 '18 at 20:20
That did the trick! Thatformatter
is really useful! I'll have to look into ISO8601, I'm not familiar with that at all. Thanks a million vadian, hope you're having a great weekend.
– KingTim
Nov 25 '18 at 20:26
add a comment |
First of all decode dateTimeLocal
as Date
let dateTimeLocal: Date
and add the appropriate date decoding strategy to decode the (not fully compliant) ISO 8601 string
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(formatter)
let object = try decoder.decode(T.self, from: data)
In the view controller class add a static date formatter on the top level
let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMMM dd, yyyy '@' h:mma"
return formatter
}()
and in cellForRow
assign the formatted date
cell.eventTimeLabel.text = dateFormatter.string(from: event.dateTimeLocal)
Thanks vadian you're a huge help as always - the date decoding strategy that you suggest will go in thedo
portion of thefetchData
function (thanks to you for help with that as well)? Or shall I make a separate function to handle the dates?
– KingTim
Nov 25 '18 at 20:06
Just replace the singledecode
line in thedo
block with the 3 lines
– vadian
Nov 25 '18 at 20:08
Got it - I'm getting an errordataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "datetime_local", intValue: nil)], debugDescription: "Expected date string to be ISO8601-formatted.", underlyingError: nil))
. I'm not changing anything in my call tofetchData
inviewDidLoad
am I?
– KingTim
Nov 25 '18 at 20:11
1
Darn, the string is not fully ISO8601 compliant (the trailing Z is missing). I updated the answer.
– vadian
Nov 25 '18 at 20:20
That did the trick! Thatformatter
is really useful! I'll have to look into ISO8601, I'm not familiar with that at all. Thanks a million vadian, hope you're having a great weekend.
– KingTim
Nov 25 '18 at 20:26
add a comment |
First of all decode dateTimeLocal
as Date
let dateTimeLocal: Date
and add the appropriate date decoding strategy to decode the (not fully compliant) ISO 8601 string
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(formatter)
let object = try decoder.decode(T.self, from: data)
In the view controller class add a static date formatter on the top level
let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMMM dd, yyyy '@' h:mma"
return formatter
}()
and in cellForRow
assign the formatted date
cell.eventTimeLabel.text = dateFormatter.string(from: event.dateTimeLocal)
First of all decode dateTimeLocal
as Date
let dateTimeLocal: Date
and add the appropriate date decoding strategy to decode the (not fully compliant) ISO 8601 string
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(formatter)
let object = try decoder.decode(T.self, from: data)
In the view controller class add a static date formatter on the top level
let dateFormatter : DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMMM dd, yyyy '@' h:mma"
return formatter
}()
and in cellForRow
assign the formatted date
cell.eventTimeLabel.text = dateFormatter.string(from: event.dateTimeLocal)
edited Nov 25 '18 at 20:19
answered Nov 25 '18 at 19:52
vadianvadian
153k17162189
153k17162189
Thanks vadian you're a huge help as always - the date decoding strategy that you suggest will go in thedo
portion of thefetchData
function (thanks to you for help with that as well)? Or shall I make a separate function to handle the dates?
– KingTim
Nov 25 '18 at 20:06
Just replace the singledecode
line in thedo
block with the 3 lines
– vadian
Nov 25 '18 at 20:08
Got it - I'm getting an errordataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "datetime_local", intValue: nil)], debugDescription: "Expected date string to be ISO8601-formatted.", underlyingError: nil))
. I'm not changing anything in my call tofetchData
inviewDidLoad
am I?
– KingTim
Nov 25 '18 at 20:11
1
Darn, the string is not fully ISO8601 compliant (the trailing Z is missing). I updated the answer.
– vadian
Nov 25 '18 at 20:20
That did the trick! Thatformatter
is really useful! I'll have to look into ISO8601, I'm not familiar with that at all. Thanks a million vadian, hope you're having a great weekend.
– KingTim
Nov 25 '18 at 20:26
add a comment |
Thanks vadian you're a huge help as always - the date decoding strategy that you suggest will go in thedo
portion of thefetchData
function (thanks to you for help with that as well)? Or shall I make a separate function to handle the dates?
– KingTim
Nov 25 '18 at 20:06
Just replace the singledecode
line in thedo
block with the 3 lines
– vadian
Nov 25 '18 at 20:08
Got it - I'm getting an errordataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "datetime_local", intValue: nil)], debugDescription: "Expected date string to be ISO8601-formatted.", underlyingError: nil))
. I'm not changing anything in my call tofetchData
inviewDidLoad
am I?
– KingTim
Nov 25 '18 at 20:11
1
Darn, the string is not fully ISO8601 compliant (the trailing Z is missing). I updated the answer.
– vadian
Nov 25 '18 at 20:20
That did the trick! Thatformatter
is really useful! I'll have to look into ISO8601, I'm not familiar with that at all. Thanks a million vadian, hope you're having a great weekend.
– KingTim
Nov 25 '18 at 20:26
Thanks vadian you're a huge help as always - the date decoding strategy that you suggest will go in the
do
portion of the fetchData
function (thanks to you for help with that as well)? Or shall I make a separate function to handle the dates?– KingTim
Nov 25 '18 at 20:06
Thanks vadian you're a huge help as always - the date decoding strategy that you suggest will go in the
do
portion of the fetchData
function (thanks to you for help with that as well)? Or shall I make a separate function to handle the dates?– KingTim
Nov 25 '18 at 20:06
Just replace the single
decode
line in the do
block with the 3 lines– vadian
Nov 25 '18 at 20:08
Just replace the single
decode
line in the do
block with the 3 lines– vadian
Nov 25 '18 at 20:08
Got it - I'm getting an error
dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "datetime_local", intValue: nil)], debugDescription: "Expected date string to be ISO8601-formatted.", underlyingError: nil))
. I'm not changing anything in my call to fetchData
in viewDidLoad
am I?– KingTim
Nov 25 '18 at 20:11
Got it - I'm getting an error
dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "events", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "datetime_local", intValue: nil)], debugDescription: "Expected date string to be ISO8601-formatted.", underlyingError: nil))
. I'm not changing anything in my call to fetchData
in viewDidLoad
am I?– KingTim
Nov 25 '18 at 20:11
1
1
Darn, the string is not fully ISO8601 compliant (the trailing Z is missing). I updated the answer.
– vadian
Nov 25 '18 at 20:20
Darn, the string is not fully ISO8601 compliant (the trailing Z is missing). I updated the answer.
– vadian
Nov 25 '18 at 20:20
That did the trick! That
formatter
is really useful! I'll have to look into ISO8601, I'm not familiar with that at all. Thanks a million vadian, hope you're having a great weekend.– KingTim
Nov 25 '18 at 20:26
That did the trick! That
formatter
is really useful! I'll have to look into ISO8601, I'm not familiar with that at all. Thanks a million vadian, hope you're having a great weekend.– KingTim
Nov 25 '18 at 20:26
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53471199%2fconverting-utc-time-in-swift%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown