Search code examples
xcodecocoa-bindings

Date Time Display Issue


I have the following code:

NSString *dateString = @"01-02-2010 12:00:00 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy h:m:s a"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];

When I set the above date in a DateTimePopup it shows "02/01/2010".

But when I use the same to add data to a GridView it shows Full Date with Time and Zone.

I need to display only Date ie "02/01/2010"

kindly help


Solution

  • You need to set the date format for display:

    NSString *dateString = @"01-02-2010 12:00:00 AM";  
    NSDateFormatter *inputDateFormatter = [NSDateFormatter new];
    [inputDateFormatter setDateFormat:@"dd-MM-yyyy h:m:s a"];
    NSDate *dateFromString = [inputDateFormatter dateFromString:dateString];
    
    NSDateFormatter *displayDateFormatter = [NSDateFormatter new];
    [displayDateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSString *displayDateString = [displayDateFormatter stringFromDate:dateFromString];
    NSLog(@"displayDateString: %@", displayDateString);
    

    NSLog output
    displayDateString: 02/01/2010

    Note: In the OP code the line
    NSDate *dateFromString = [[NSDate alloc] init];
    is unnecessary, on the very next line dateFromString is over written.