PrasathBabu
PrasathBabu

Reputation: 4846

NSDateFormatter Issue - Getting wrong date

In iPhone Device, getting wrong DateTime Format for customer device from our Production App.

we using DateTime format as yyyy-MM-dd HH:mm:ss and replace empty with T and excepted result as 2018-07-13T15:07:36, but getting date time as 2018-07-13T3:07:36TPM

Steps to Reproduce: Method to get DateTime String

+ (NSString *)getCurrentLocalDateTime
{
    NSDate *localDate = [NSDate date];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *dateString = [dateFormatter stringFromDate:localDate];
    dateString = [dateString stringByReplacingOccurrencesOfString:@" " withString:@"T"];
    NSLog(@"CURR: %@", dateString);

    return dateString; // yyyy-MM-ddTHH:mm:ss
}

Expected Results: Output Data must be - 2018-07-13T15:07:36

Actual Results: Actual Data - 2018-07-13T3:07:36TPM

issue happend in iOS Version - 11.3.1 and 11.1.2

Upvotes: 0

Views: 85

Answers (2)

vadian
vadian

Reputation: 285290

Just insert the T wrapped in single quotes into the date format to get the literal "T"

@"yyyy-MM-dd'T'HH:mm:ss"

According to Technical Q&A QA1480 for fixed-format dates set the locale of the date formatter to the fixed value en_US_POSIX:

+(NSString *)getCurrentLocalDateTime
{
    NSDate *localDate = [NSDate date];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:localDate];
    NSLog(@"CURR: %@", dateString);

    return dateString; // yyyy-MM-ddTHH:mm:ss
}

Upvotes: 3

Following is the example of NSDateFormatter. You can use it and customise it's order of day:month:year

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy HH:mm"];

NSDate *currentDate = [NSDate date];
NSString *dateString = [formatter stringFromDate:currentDate];

Upvotes: -2

Related Questions