How do I get the alphanumeric abbreviated day of month in objective-c? - objective-c

NSDate in Objective-c used to have dateWithNaturalLanguageString which accepted the use of abbreviated alphanumeric days of month with in strings like: #"Aug 2nd, 2010", but this method is deprecated, and I am trying to use NSDateFormatter instead:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM dd, yyyy"];
but I can not use the following string with the above format:
NSDate date* = [dateFormatter dateFromString:#"Aug 2nd, 2010"];
since it will cause the date to be null due to incompatible format. I checked out the unicode standard date formats but I could not find anything that has an abbreviated alphanumeric day of month, and I am forced to use #"Aug 02, 2010" instead. But this is not desirable since I need abbreviated alphanumeric day of month both for setting a date from a string and getting a string from a date. After searching hours through various documentations I am out of ideas. Is there anyway other than the deprecated dateWithNaturalLanguageString? Or do I have to make a method of my own?

NSDateFormatter does not support ordinal suffixes (in English).
An alternative is to remove the suffix with Regular Expression
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
dateFormatter.dateFormat = #"MMM dd, yyyy";
NSString *dateString = #"Aug 2nd, 2010";
NSString *trimmedString = [dateString stringByReplacingOccurrencesOfString:#"(\\d{1,2})(st|nd|rd|th)"
withString:#"$1"
options: NSRegularExpressionSearch
range:NSMakeRange(0, dateString.length)];
NSDate *date = [dateFormatter dateFromString:trimmedString];
NSLog(#"%#", date);

Related

NSDateFormatter returns nil with format YYYY-MM-ddTHH:mm:ssZ

I'm trying to get the NSDate from a string with the following format 'YYYY-MM-ddTHH:mm:ssZ' using the NSDateFormatter. The NSDateFormatter returns always nil. Here is how I tried to do that:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"YYYY'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate *dateFromString = [dateFormatter dateFromString:#"2013-08-09T18:30:00+02:00"];
that would be a better formatter.
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
Your date format string should be as follows:
#"yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"
Note the lower cased 'yyyy'. The uppercase Y means "Week of Year" based calendar.
See this answer: Difference between 'YYYY' and 'yyyy' in NSDateFormatter and the Unicode standard for more info: http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns

Date with month name date, year in objective-c

I have a date string formatted as "September 10, 2013". How can I convert this representation into a format such as "yyyy/mm/dd".
NSString *strDate = #"September 10, 2013";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df dateFromString:strDate];
NSDate *date = [df dateFromString:strDate];
[df setDateFormat:#"yyyy/mm/dd"];
NSString* temp = [[NSString alloc] init];
temp = [df stringFromDate:date];
NSLog(#"date i required %#", temp);
temp object is null here.
Thanks in advance.
Let's rework your original code, and discuss it as well:
NSString *strDate = #"September 10, 2013";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
For the input you're attempting to parse, you've got to provide a format string for your date formatter. If you don't, the date formatter is going to use defaults that are determined by the settings in your Date & Time control panel. Not only do these settings vary from locale to locale, they're subject to whatever changes the user may have effected. Another way of putting it is that they might not match the format of the date string you're attempting to convert.
You also don't want to rely on predefined styles such as NSDateFormatterShortStyle, NSDateFormatterMediumStyle or NSDateFormatterLongStyle. They're meant for date display (if you're willing to accept the Date & Time control panel settings), not for parsing.
There's a document you should consult, which is Unicode Technical Standard #35. Look in the table labeled "Date Field Symbol Table." Based on the information presented there (and your input), you'd set up your date converter to parse with a format string like this one:
[df setDateFormat:#"MMMM dd, yyyy"];
Now you can use your date formatter to parse your date string, and it'll work:
NSDate *date = [df dateFromString:strDate];
From this point onward, you're looking pretty good (though I've removed a superfluous line or two throughout all of this):
[df setDateFormat:#"yyyy/MM/dd"];
NSString *temp = [df stringFromDate:date];
NSLog(#"date i required %#", temp);
Best wishes to you in your endeavors.
You can use the NSDateFormatterclass -- look at the stringFromDate and dateFromString methods.
UPDATE: you have a couple of problems -- first, you need to tell the formatter what the initial format should be. Second, you have a format problem with the second format string -- 'm' is minutes, 'M' is months. You should review the documentation here. Here is an example:
NSString *strDate = #"September 10, 2013";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterLongStyle];
[df dateFromString:strDate];
NSDate *dat = [df dateFromString:strDate];
[df setDateFormat:#"yyyy/MM/dd"];
NSString* t = [df stringFromDate:dat];
NSLog(#"date i required %#", t);

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

Why isn't my time zone being saved into my NSDate?

I must initialize an NSDate object from NSString in objective-c. I do it like this:
NSString *dateString = [[webSentence child:#"DateTime"].text stringByReplacingOccurrencesOfString:#"T" withString:#" "];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-mm-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Budapest"]];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
E.g: when I try it with string value #"2011-01-02 17:49:54" I get an NSDate 2011-01-02 16:49:54 +0000. As you can see there is a one hour difference between the two values. NSDate has a wrong value, it should be exactly the same I defined in my string in the timezone I set in dateFormatter. It seems it uses my date defined it string as UTC, even if I set its timezone to "Europe/Budapest". How can I fix this problem?
Thanks!
NSDate stores dates relative to a standard reference date. From the class docs:
"The sole primitive method of NSDate, timeIntervalSinceReferenceDate, provides the basis for all the other methods in the NSDate interface. This method returns a time value relative to an absolute reference date—the first instant of 1 January 2001, GMT."
NSDate does not itself have any concept of time zones. So the NSDateFormatter did the right thing: it converted a date which you told it had a GMT offset (by specifying a time zone), and gave you a "normalized" NSDate for that date.
If you want to see the date represented in the Europe/Budapest time zone, either use your existing date formatter (-stringFromDate:) or the appropriate NSDate description method (e.g. -descriptionWithCalendarFormat:timeZone:locale:).
P.S.- You don't need an alloc/init at all in your code as written. In non-ARC that would be a leak.
P.P.S.- Your date format is incorrect and giving nonsensical results. I've gone ahead and cleaned up your code as follows (tested under ARC):
NSString *dateString = #"2011-09-02 17:49:54";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *tz = [NSTimeZone timeZoneWithName:#"Europe/Budapest"];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:tz];
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(#"%#", [dateFormatter stringFromDate:date]);
NSLog(#"%#", [date descriptionWithCalendarFormat:nil timeZone:tz locale:nil]);
Two things:
1) you have an error in your date format string. You should use MM for month, not mm (lowercase mm is for minutes)
2) after you create you NSDate object, you'll need to use the NSDateFormatter method stringFromDate: to generate a date string localized to a particular timezone. If you just do a straight NSLog() on the NSDate object it will show the date as GMT by default (GMT is one hour behind Budapest time)

How do I convert from NSString to NSDate using NSDateFormater

I have this string: 2012-01-12T21:01:00 and this code:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd hh:mm:ss a"];
NSDate* arrivalTime=[df dateFromString:field_arrival_time];
But it returns nil. What date format should I use to parse this string?
Your string 2012-01-12T21:01:00 contains the literal T (At least I believe it's a literal, it doesn't appear to signify a timezone). You must include this in your date format.
[df setDateFormat:#"yyyy-MM-dd'T'hh:mm:ss"];
Note the lack of the a in the date format, using it will require your input string to use AM or PM preceded by a white space. For more information on special characters with NSDateFormatter take a look at the Date Formatting Guide paying extra attention to the Fixed Formats.
Edit: Your input string does not specify a timezone, it will probably be interpreted as UTC and be localized to the timezone of your machine when you output it through NSLog().
I have tried a lot on your string but never get result. only nil shows on console. but when i remove character "T" from your string it gives perfect result.
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:#"2012-01-12 21:01:00"];
NSLog(#"date %#", date);
NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
[f2 setDateFormat:#"dd-MM-yyyy"];
NSString *s = [f2 stringFromDate:date];
NSLog(#"S %#", s);
/// OutPut : S 12-01-2012