JSON date to NSDate Issue - objective-c

I have a date string in JSON format, it looks like this:
2013-05-22T10:54:40.437
And I'm trying to convert it to NSDate.
- (NSString *)dateFromString:(NSString *)datestring{
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss"];
NSDate *date = [dateFormat dateFromString:datestring];
//date is nil here.
NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:#"MM/dd/yyyy"];
NSString *newString = [newDateFormatter stringFromDate:date];
NSLog(#"Date -- %#",datestring);
return newString;
}
But date is nil after dateFromString. Does anyone know what I did wrong here?
Thanks!

Use this date format:
yyyy-MM-dd'T'HH:mm:ss.SSS
Your code with little modification:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSDate *date = [dateFormat dateFromString:datestring];
NSDateFormatter *newDateFormatter = [[NSDateFormatter alloc]init];
[newDateFormatter setDateFormat:#"MM/dd/yyyy"];
NSString *newString = [newDateFormatter stringFromDate:date];
NSLog(#"Date: %#, formatted date: %#", date, newString);
gives me this output:
Date: 2013-05-22 08:54:40 +0000, formatted date: 05/22/2013
Edit: how "ikinci viking" pointed out in comment, escaping the dashes is unnecessary. Escaping removed from the code
Update for iOS 11+
ISO8601DateFormatter is the recommended way to parse internet date on iOS 10+.
However it has few issues preventing it from usage with the specific format from the question:
Milliseconds are supported only on iOS 11+
It does not work for dates without timezone (the case in question). Date string must contain timezone part (e.g. +00:00 or Z for "Zulu time" UTC)
If date strings contains both milliseconds and timezone (e.g. 2018-09-07T14:04:13.143Z), it can be used as follows (Swift example):
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]

Your date format is incorrect. It should be:
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss:SSS"];
The three capital 'S' means it will take the fractional part to 3 digits. Adjust it as you will.

If your date format is "2014-02-25T13:05:10+00:00" then,
your code should be like this....
NSURL *url = [NSURL URLWithString:#"your URL"];
NSString *str = [[NSString alloc] initWithContentsOfURL:url usedEncoding:Nil error:Nil];
NSDateFormatter *dateFor = [[NSDateFormatter alloc] init];
[dateFor setDateFormat:**#"yyyy-MM-dd'T'HH:mm:ss'+'SS:SS"**];
NSDate *yourDate = [dateFor dateFromString:str];
NSLog(#"Your Date: %#",yourDate);

-(void)viewDidLoad {
self.date = [dateForRFC3339DateTimeString:#"2015-01-18T01:00:00.000Z"];
}
-(NSDate *)dateForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString {
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to a NSDate.
NSDate *result = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
return result;
}

Related

How to get only date from ISO8601 timestamp to as string ios?

Hi i have date format in ISO8601 as example:
NSString *currentDateString = #"2016-01-12T21:21:22.737+05:30";
i want to get only date which is 2016-01-12 from this string:
i tried
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];
NSLog(#"CurrentDate:%#", currentDate);
its retuning null but i want to get date in format of yyyy-MM-dd.
Please try this code.
NSString *dateString = #"2013-04-18T08:49:58.157+0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
// Always use this locale when parsing fixed format date strings
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[formatter setLocale:posix];
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"date = %#", date);
Found a solution using NSRange:
NSString *currentDateString = #"2016-01-12T21:21:22.737+05:30";
NSRange range = [currentDateString rangeOfString:#"T"];
NSString *newString = [currentDateString substringToIndex:range.location];
NSLog(#"%#",newString);

Convert a string timezone to NSTimeZone

I have a time zone formatted like this in an incoming string which I have no control over (it comes in a dictionary from server)
tzHours = NSString * #"+01:00"
But I need to convert it into a NSTimeZone so I can format a date
NSString *date = [dateDictionary safeObjectForKey:#"date"];
NSString *time = [dateDictionary safeObjectForKey:#"time"];
NSString *tzHours = [dateDictionary safeObjectForKey:#"timeZone"];
// Format the date based off the timezone
NSDateFormatter *formatter = [self _apiDateFormatterWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
But I am unsure how to do this.
Is there a good way to do handle this?
Many thanks
So given you have the three NSStrings: date, time and tzHours. You could do something like this:
NSString *date = #"2015-01-01";
NSString *time = #"14:00:01";
NSString *tzHours = #"+01:00";
NSString *dateString = [NSString stringWithFormat:#"%# %# %#", date, time, tzHours];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd HH:mm:ss ZZZZZ";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
NSDate *dateObject = [dateFormatter dateFromString:dateString];
The dateFormat of the NSDateFormatter naturally depends on the format of date and time.
Also remember to cache the NSDateFormatter or else you will suffer performance-wise.

How to convert Date from JSON to NSDate

Hi I need to convert this string
"2013-12-05T08:58:55.9345456+02:00"
to NSDate
I am trying next format but without luck
"yyyy-MM-dd'T'HH:mm:SSSSSSSZZZZZ"
Code below.
Can you help me with right format
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// "2013-12-05T08:58:55.9345456+02:00"
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:SSSSSSSZZZZZ"];
NSDate *date = [dateFormat dateFromString:jsonDateString];
Your format is close. You need:
yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZZZZZ
And be sure to set the formatter's locale to en_US_POSIX. This should always be done when parsing fixed formatted, non-localized strings.
NSString * dateStr = #"2013-12-05T08:58:55.9345456+02:00";
NSArray *dateStrParts = [dateStr componentsSeparatedByString:#"T"];
NSString *datePart = [dateStrParts objectAtIndex:0];
NSString *timePart = [dateStrParts objectAtIndex:1];
NSString *t = [[timePart componentsSeparatedByString:#"."] objectAtIndex:0];
NSString *newDateStr = [NSString stringWithFormat:#"%# %#",datePart,t];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"]; // Change here for your formated output
NSDate *date = [df dateFromString:newDateStr];
NSLog(#"%#",date);
Output
2013-12-05 08:58:55 +0000
The problem lies in the timezone where you have +02:00.
The ZZZZ only parses to +0000, hence you are getting nil.
You can do in this way:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString *jsonDateString = #"2013-12-05T08:58:55.9345456+02:00";//#"2013-12-05T08:58:55.9345456+02:00"
NSRange lastColon = [jsonDateString rangeOfString:#":" options:NSBackwardsSearch];
if(lastColon.location != NSNotFound) {
jsonDateString = [jsonDateString stringByReplacingCharactersInRange:lastColon withString: #""];
}
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'.'SZ"];
NSDate *date = [dateFormat dateFromString:jsonDateString];
NSLog(#"%#",date)
EDIT:
As per rmaddy's comment, you should use SSSSS instead of single S.

Convert NSString to NSDate to compare which one is newer?

First time caller, long time listener :) Love this site. I'm new to Objective-C but have a blast learning. I'm sorry for such a simple question but I can't figure this out. :(
I have two NSStrings in the format:
itemdate: [March 1, 2013] lastloaddate: [January 1, 1980]
I want to find out which string (date) is most recent. To do this I'm trying to convert the NSString to NSDate and then do a compare but i'm not having any luck. Here is my code. Any and all help would be greatly appreciated!
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate *titemdate = [df dateFromString: itemdate];
NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
[df1 setDateFormat:#"yyyy-MM-dd"];
NSDate *tlasttimerundate = [df1 dateFromString: lastdate];
if ([tlasttimerundate compare:titemdate] == NSOrderedDescending)
{
NSLog(#"itemdate is newer than lastdate");
}
Use [df setDateFormat:#"MMMM d,YYYY"]; instead of [df setDateFormat:#"yyyy-MM-dd"];
The MMMM format will get the full date month where as the MM format will just the months number. For example MM is 5 and MMMMM is May.
To achieve the date compare:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MMMM d,YYYY"];
df.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"EN"];
NSDate *titemdate = [df dateFromString: itemdate];
NSDate *tlasttimerundate = [df dateFromString: lastdate];
if ([tlasttimerundate compare:titemdate] == NSOrderedDescending)
{
NSLog(#"itemdate is newer than lastdate");
}
You can find more about the date formats here: http://unicode.org/reports/tr35/tr35-10.html#Date_Format_Patterns

Convert date in MM/dd/yyyy format in xcode?

I have a UIDatePicker and I m getting the selected date from it in yyyy-MM-dd format.Now I want to convert it to MM/dd/yyyy format ..How can i do it ?
NSDateFormatter *df=[[[NSDateFormatter alloc]init] autorelease];
df.dateFormat = #"yyyy-MM-dd";
NSArray *temp=[[NSString stringWithFormat:#"%#",[df stringFromDate:DatePicker.date]] componentsSeparatedByString:#""];
[dateString2 release];
dateString2=nil;
dateString2= [[NSString alloc]initWithString:[temp objectAtIndex:0]];
NSLog(#"%#",dateString2);
Im getting 2012-10-30 but I want 10/30/2012.
See Instruction or introduction with every line
NSString *str = #"2012-10-30"; /// here this is your date with format yyyy-MM-dd
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; // here we create NSDateFormatter object for change the Format of date..
[dateFormatter setDateFormat:#"yyyy-MM-dd"]; //// here set format of date which is in your output date (means above str with format)
NSDate *date = [dateFormatter dateFromString: str]; // here you can fetch date from string with define format
dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];// here set format which you want...
NSString *convertedString = [dateFormatter stringFromDate:date]; //here convert date in NSString
NSLog(#"Converted String : %#",convertedString);
df.dateFormat = #"MM/dd/yyyy";
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MM/dd/yyyy"];
Just to see how it ends up:
NSDateFormatter* df = [[[NSDateFormatter alloc]init] autorelease];
df.dateFormat = #"MM/dd/yyyy";
NSString* dateString = [df stringFromDate:datePicker.date]; // Don't use leading caps on variables
NSLog(#"%#", dateString);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
The original accepted answer does a few things extra:
1) It allocates two NSDateFormatter instances which is not required. NSDateFormatter is expensive to create.
2) It is better to release date formatters explicitly when you are done with them rather than a deferred release using autorelease.
//get datepicker date (NSDate *)
NSDate *datePickerDate = [myDatePicker date];
//create a date formatter
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//set its format as the required output format
[formatter setDateFormat:#"MM/dd/yyyy"];
//get the output date as string
NSString *outputDateString = [formatter stringFromDate:datePickerDate];
//release formatter
[formatter release];
- (void)showTime {
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"HH:mm:ss"];
// you label
_time.text = [dateFormatter stringFromDate:now];
}
- (void)showDate {
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
// you label
_date.text = [dateFormatter stringFromDate:now];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.showTime;
self.showDate;
}
Enjoy
NSString *str = #"2012-10-30"; /// here this is your date with format yyyy-MM-dd
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; // here we create NSDateFormatter object for change the Format of date..
[dateFormatter setDateFormat:#"yyyy-MM-dd"]; //// here set format of date which is in your output date (means above str with format)
NSDate *date = [dateFormatter dateFromString: str]; // here you can fetch date from string with define format
dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];// here set format which you want...
NSString *convertedString = [dateFormatter stringFromDate:date]; here convert date in NSString
NSLog(#"Converted String : %#",convertedString);
I use a code with options NSISO8601DateFormatWithDashSeparatorInDate:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString * stringformat = [NSDateFormatter dateFormatFromTemplate:#"MMddy" options:NSISO8601DateFormatWithDashSeparatorInDate locale:[NSLocale systemLocale]];
[dateFormatter setDateFormat:stringformat];
NSDate *d = [NSDate date]; // or set your date
NSLog(#"date in format %#", [dateFormatter stringFromDate:d]); // date in format 2018-06-20