Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way of converting an ISO8601 timestamp to a formatted NSDate?

If I use the following code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm"]; NSDate *myDate = [dateFormatter dateFromString:@"2010-01-28T15:22:23.863"]; NSLog(@"%@", [dateFormatter stringFromDate:myDate]); 

It is successfully converted to a Date object, however, I cannot seem to format it any other way than yyyy-MM-dd'T'HH:mm, i.e. what gets logged is 2010-01-28T15:22:23

If I change the dateFormat to say [dateFormatter setDateFormat:@"yyyy-MMMM-d'T'HH:mm"]; the Date object is null...

So my ultimate question is how to format an ISO8601 timestamp from a SQL database to use, for instance, NSDateFormatterMediumStyle to return "January 1, 2010"?

like image 440
rson Avatar asked Feb 04 '10 16:02

rson


People also ask

How do I format a date in ISO 8601?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

What is the standard timestamp format?

As of ISO 8601-1:2019, the basic format is T[hh][mm][ss] and the extended format is T[hh]:[mm]:[ss]. Earlier versions omitted the T (representing time) in both formats. [hh] refers to a zero-padded hour between 00 and 23. [mm] refers to a zero-padded minute between 00 and 59.

What is ISO 8601 date format Java?

The Date/Time API in Java works with the ISO 8601 format by default, which is (yyyy-MM-dd) . All Dates by default follow this format, and all Strings that are converted must follow it if you're using the default formatter.


1 Answers

I have a similiar but slightly more complex problem, and I've found a very simple solution!

The problem: My incoming ISO8601 dates look like this: 2006-06-14T11:06:00+02:00 They have a timezone offset at the end.

The solution: Use Peter Hosey's ISO8601DateFormatter which you can download from here.

ISO8601DateFormatter *formatter = [[ISO8601DateFormatter alloc] init]; NSDate *theDate = [formatter dateFromString:dateString]; [formatter release], formatter = nil; 

and

ISO8601DateFormatter *formatter = [[ISO8601DateFormatter alloc] init]; NSString *dateString = [formatter stringFromDate:[twitch dateTwitched]]; [formatter release], formatter = nil; 
like image 124
Matthew Avatar answered Sep 30 '22 20:09

Matthew