2

I am trying to convert NSString to NSdate. The string has date in it.i use the following

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"MM/dd/yyyy"];
NSDate *date = [dateFormat dateFromString:setitempricedate];
NSLog(@"Date : %@",date);

the input string contains the date in the format 02/08/2011 when i log date , i get 2011-02-07 18:30:00 GMT,

I want to get the date as 02/08/2011 only. Where am i going wrong

1

3 Answers 3

5

In your code, you are asking the date formatter to create a date object for you from a given string. Then you printed out that date object. What you want is to create that date object, then ask the date formatter to format that date object you just created. You should be calling stringFromDate instead.

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"MM/dd/yyyy"];
NSDate *date = [dateFormat dateFromString:setitempricedate];
NSLog(@"Date: %@", [dateFormat stringFromDate:date]);
1
  • this NSLog(@"Date: %@", [dateFormat stringFromDate:date]);
    – pradeep
    Feb 11, 2011 at 7:13
0

You will not be able to change the date representation. These (NSDateFormatter, NSCalendar) classes are provided to get formatted strings not date.

Whenever you will have an instance of NSDate class it will be in same format like you are getting.

2011-02-07 18:30:00 GMT

If you want custom styles better you go with NSString

-1

You are printing the actual date object which doesn't follow the date format you specified. You could do something like

[[NSDate dateWithString:setitempricedate] stringFromDate];
2
  • [NSDate dateWithString:setitempricedate] is available in mac not iOS Feb 11, 2011 at 6:54
  • Oops :) for some reason my google search for 'ios iphone nsdate reference' returned the mac docs :/ good catch
    – raidfive
    Feb 11, 2011 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.