-6

I know there are lot of questions on this topic . But I am not getting a proper solution to my

problem.I am retrieving Date from db , I am getting the Output as

as 2012-07-13 00:00:00.0 .

I am getting the output in the string format . I want the result of type string in the

format MM/dd/yyyy.I am doing the following

NSString *dateStr=@"2012-07-13 00:00:00.0";

NSDateFormatter *df=[NSDateFormatter new];

[df setDateFormat:@"yyyy-MM-dd"];

NSDate *res=[df dateFromString:dateStr];

But here I am getting res as nil .

Raj
  • 1,119
  • 1
  • 15
  • 32
  • I just googled your question, and see what I got, https://www.google.co.in/search?q=Converting+Date+to+MM%2Fdd%2Fyy+format&aq=f&oq=Converting+Date+to+MM%2Fdd%2Fyy+format&aqs=chrome.0.57.521j0&sourceid=chrome&ie=UTF-8 – rptwsthi May 17 '13 at 04:46
  • @rptwsthi : please read the entire content of my question just before down voting it. – Raj May 17 '13 at 04:53

4 Answers4

2

You need to tell the formatter the whole format of the date, including hours, minutes...

This works:

NSString *dateStr=@"2012-07-13 00:00:00.0";

NSDateFormatter *df=[NSDateFormatter new];

[df setDateFormat:@"yyyy-MM-dd hh:mm:ss.S"];

NSDate *res=[df dateFromString:dateStr];

[df setDateFormat:@"MM/dd/yyyy"];

NSString *myString =[df stringFromDate:res]; 
Antonio MG
  • 20,382
  • 3
  • 43
  • 62
0

try this:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.s"];
NSDate *aDate=[formatter dateFromString:[NSString stringWithFormat:@"%@", @"2012-07-13 00:00:00.0"]];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSLog(@"%@", [dateFormatter stringFromDate:aDate]);
Vaibhav Saran
  • 12,848
  • 3
  • 65
  • 75
0

Use this one

 NSString *dateStr=@"2012-07-13 00:00:00.0";
 NSDateFormatter *df = [[NSDateFormatter alloc] init];
 [df setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];  

  NSDate *date = [df dateFromString: dateStr]; 

  [df setDateFormat:@"MM/dd/yyyy"];

  NSString *convertedString = [df stringFromDate:date]; 
  NSLog(@"Your String : %@",convertedString);

Output: Your String : 07/13/2012

Dharmbir Singh
  • 17,485
  • 5
  • 50
  • 66
0

Try this

    NSString *dateStr=@"2012-07-13 00:00:00.0";
    NSDateFormatter *dateFormatter=[NSDateFormatter new];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss.S"];
    NSDate *dateObj=[dateFormatter dateFromString:dateStr];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSString *myString = [dateFormatter stringFromDate:dateObj];
    NSLog(@"%@",myString);
Lithu T.V
  • 19,955
  • 12
  • 56
  • 101