How to convert an NString to an NSDate and then set the date to a UILabel - objective-c

I need to convert the following string into a better readable format:
NSString *deadlineFromTable = #"2012-11-13T22:59:00.000Z";
I would like to convert this into an NSDate, so I can format it.
I tried the following, but I get an incompatible pointer error assigning NSString to NSDate when I try to set it to a UILabel (the last line):
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:deadlineFromTable];
self.deadlineLbl.text = dateFromString;
Thanks for any help.

You need to use the dateFormatter twice. Once for parsing, and once for formatting your string.
You cannot assign a date as a label text directly.
Set format: yyyy-MM-dd'T'HH:mm:ss.Z and then use
NSDate *date = [dateFormatter dateFromString:dedlineFromTable];
Set format: dd-MM-yyyy and then use
NSString *text = [dateFormatter stringFromDate: date];

You need two dateFormatters.
One to convert from your input string to a date and then one to convert from that date into the Label format you want.
You also need to change the format of the date formatter so it matches your string...
NSDateFormatter *dateStringParser = [[NSDateFormatter alloc] init];
[dateStringParser setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.Z"];
NSDate *date = [dateStringParser dateFromString:deadlineFromTable];
NSDateFormatter *labelFormatter = [[NSDateFormatter alloc] init];
[labelFormatter setDateFormat:#"dd-MM-yyyy"];
self.deadlineLbl.text = [labelFormatter stringFromDate:date];
That should do it.

Related

NSDateFormatter returns nil

I'm trying to parse a date passed in the format:
"2014-03-26T05:07:42.14286Z"
My NSDateFormatter code looks like this
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'SS'Z'"];
self.createdAt = [dateFormatter dateFromString:#""2014-03-26T05:07:42.14286Z""];
But it just returns nil. I've tried multiple variations with and without the ticks but I seem to be missing something. Am I using NSDateFormatter incorrectly, misunderstanding the usage of ticks or something else entirely?
The formatter returns nil if the given string doesn't correspond to the expected format. Your format string was almost right, you just needed to :
Apostrophe should only be used for literals
Milliseconds should be specified as 'SSS' and match the separation (use ss.SSS)
The correct format string is :
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *d = [df dateFromString:#"2014-03-26T05:07:42.14286Z"];
Just replace the below line to modified line
[dateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'SS'Z'"];
Modified line:-
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];

Date not displayed properly in the nib file

I have a string with value #"15/11/13". I need to display the same on the label in the nib file.
I am using the following code to display it
NSDateFormatter * df1 = [[NSDateFormatter alloc] init];
[df1 setDateFormat:#"yyyy-mm-dd"];
[df1 setDateStyle:NSDateFormatterShortStyle];
[df1 setTimeStyle:NSDateFormatterNoStyle];
[profile1 setLastPromotionDate:[df1 dateFromString:#"11/11/13"]];
Profile1 is a different class which has lastPromotonDate of type NSDate.
In the nib file I have a outlet to display date which is bound to lastPromotionDate.
When I run the app, the date displayed is Monday, 11 November 2013 12:00:00 AM India Standard Time.
Can I know what is the mistake here? What has to be done so the date displays in this format : 11/11/13
Try this:-
NSString *dateStr=#"11/11/13";
NSDateFormatter *format=[[[NSDateFormatter alloc]init]autorelease];
[format setDateFormat:#"dd/mm/yy"];
NSDate *dt=[format dateFromString:dateStr];
NSString *str=[format stringFromDate:dt];
NSLog(#"%#",str);
NSString *str = #"15/11/13";
// here we create NSDateFormatter object for change the Format of date..
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
// here set format of date which is in your output date (means above str with format)
[dateFormatter setDateFormat:#"yy/mm/dd"];
// here you can fetch date from string with define format
NSDate *date = [dateFormatter dateFromString: str];
dateFormatter = [[NSDateFormatter alloc] init] ;
// here set format which you want..
[dateFormatter setDateFormat:#"dd/mm/yy"];
NSString *convertedString = [dateFormatter stringFromDate:date];
//here convert date in NSString
NSLog(#"Converted String : %#",convertedString);
rofile1.text = convertedString;
Why not just set it as:
NSString *str = #"15/11/13";
[label setStringValue: str];
UPDATE:
To convert this string to NSDate of the same format use:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd/mm/yy"];
NSDate * date = [df dateFromString:str];
To get back the string value of date from NSDate use:
NSString *dateStr = [df stringFromDate: date];
Also you may use this dateStr to set you label text as
[label setStringValue: dateStr];
or bind the label to "dateStr". (Do not bind it to "date" of NSDate type, I think this is where you are going wrong).
Use "date" variable that is of NSDate type for your server requests.
UPDATE:
Since you are binding your label to NSDate value, it displays the complete date in the way it is present in NSDate. To retrieve the value of that NSDate in your custom format, you need to use NSDateFormatter that will write the part of NSDate that we need in our format to a NSString.
Also if we convert a NSString to NSDate, it doesn't mean that date formatter will save the NSDate in our custom format, the format of the date formatter specify the format of our string so that NSDate could read the correct date from our custom formatted string. But NSDate will always save the date value in its own format.
We have something called DateFormatter under objects in the library. We can drag and drop that under the text cell if the label in the list view of the nib.
This data formatter converts the date format to string value which is used to display in the UI.

Convert ISO 8601 to NSDate

I have a timestamp coming from server that looks like this:
2013-04-18T08:49:58.157+0000
I've tried removing the colons, I've tried all of these:
Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?
Why NSDateFormatter can not parse date from ISO 8601 format
Here is where I am at:
+ (NSDate *)dateUsingStringFromAPI:(NSString *)dateString {
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc] init];
//#"yyyy-MM-dd'T'HH:mm:ss'Z'" - doesn't work
//#"yyyy-MM-dd'T'HH:mm:ssZZZ" - doesn't work
//#"yyyy-MM-dd'T'HH:mm:sss" - doesn't work
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
// NSDateFormatter does not like ISO 8601 so strip the milliseconds and timezone
dateString = [dateString substringWithRange:NSMakeRange(0, [dateString length]-5)];
return [dateFormatter dateFromString:dateString];
}
One of my biggest questions is, is the date format I have above really ISO 8601? All the examples I have seen from people the formats of each are slightly different. Some have ...157-0000, others don't have anything at the end.
This works for me:
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);
There is New API from Apple! NSISO8601DateFormatter
NSString *dateSTR = #"2005-06-27T21:00:00Z";
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
NSDate *date = [formatter dateFromString:dateSTR];
NSLog(#"%#", date);
I also have the native API, which is way cleaner... This is the implementation I got in my DateTimeManager class:
+ (NSDate *)getDateFromISO8601:(NSString *)strDate{
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
NSDate *date = [formatter dateFromString: strDate];
return date;
}
Just copy and paste the method, it would do the trick. Enjoy it!
The perfect and best solution that worked for me is:
let isoFormatter = ISO8601DateFormatter();
isoFormatter.formatOptions = [ISO8601DateFormatter.Options.withColonSeparatorInTime,
ISO8601DateFormatter.Options.withFractionalSeconds,
ISO8601DateFormatter.Options.withFullDate,
ISO8601DateFormatter.Options.withFullTime,
ISO8601DateFormatter.Options.withTimeZone]
let date = isoFormatter.date(from: dateStr);
For further more detail, you can refer to apple's official documentation: https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

Setting date format for particular string format in ios

I'm trying to set NSDateFormatter for the below string:
2012-12-18T09:05:24.000Z
It's the output of S3Object Summary lastmodifed object. What is the format I have to set it to if I need to change the display format?Any idea?
NSString *stringe = #"2010-06-21T20:06:36+00:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *reqDate = [dateFormatter dateFromString:string];
NSLog(#"%#",[dateFormatter stringFromDate:reqDate]);
Now you will get the date in NSDate object so you can change that date to as per your requirement.
For 2012-12-18T09:05:24.000Z
The format string is
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Objective-C – NSDateFormatter dateFromString ignore time

If I'm not interested in the time can I ignore it? I.e I have a date string that looks like this #"2012-12-19T14:00:00" but I'm only interested in getting the date (2012-12-19) but if I set NSDateFormatter like [dateFormatter setDateFormat:#"yyyy-MM-dd"]; it will return me a nil NSDate.
An NSDate object will always contain a time component as well, as it is representing a point in time — from this perspective one could argue the name NSDate is misleading.
You should create a date formatter for creating dates from string, set the time to the start of the day and use a second date formatter to output the date without time component.
NSString *dateString = #"2012-12-19T14:00:00";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateStyle:NSDateFormatterShortStyle];
[outputFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [inputFormatter dateFromString:dateString];
//this will set date's time components to 00:00
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&date
interval:NULL
forDate:date];
NSString *outputString = [outputFormatter stringFromDate:date];
NSLog(#"%#", outputString);
results in
19.12.12
while the format — as it is chosen by styling — will be dependent of your environment locale
all date string returns 10 characters for the date, what i mean is the date of todayy will be 2012-11-19
you can easily substring the date and use it as you want:
Example :
NSString* newDate = #"";
newDate = [[NSDate date]substringToIndex:10];
the out put will be : 2012-11-19