Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter and yyyy-MM-dd

I'm trying to take a NSString date in the format "2/22/11" and convert it to this format: 2011-02-22

This is my code:

NSDate *dateTemp = [[NSDate alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
dateTemp = [dateFormat dateFromString:newInvoice.date];
newInvoice.date = [dateFormat stringFromDate:dateTemp];

newInvoice.date starts as an NSString equal to "2/22/11". dateTemp ends up NIL. newInvoice.date ends up NIL as well.

I can't for the life of me figure out why.

like image 607
clifgriffin Avatar asked Feb 23 '11 04:02

clifgriffin


People also ask

Is NSDateFormatter thread safe?

Thread Safety On earlier versions of the operating system, or when using the legacy formatter behavior or running in 32-bit in macOS, NSDateFormatter is not thread safe, and you therefore must not mutate a date formatter simultaneously from multiple threads.

What format is my date in?

The United States is one of the few countries that use “mm-dd-yyyy” as their date format–which is very very unique!

What is en_US_POSIX?

In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.

How do I change the date format in IOS Swift?

We start by creating a Date object. To convert the date to a string, we need to create a date formatter, an instance of the DateFormatter class. To convert the Date object to a string, we invoke the date formatter's string(from:) instance method.


1 Answers

You are facing this problem because your date formatter is not correct.Suppose your newInvoice.date variable store "11:02:23" the your dateFormatter should be @"yy:MM:dd" and if your newInvoice.date variable store"2/22/11" then your dateFormatter should be @"MM/dd/yy"

NSDate *dateTemp = [[NSDate alloc] init];
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];

[dateFormat1 setDateFormat:@"MM/dd/yy"];
[dateFormat2 setDateFormat:@"yyyy-MM-dd"];

dateTemp = [dateFormat1 dateFromString:newInvoice.date];
newInvoice.date = [dateFormat2 stringFromDate:dateTemp];

both format should be according to your requirement to get the correct result

like image 187
Amit Singh Avatar answered Oct 09 '22 04:10

Amit Singh