-3

I'm trying to get an NSDate in a format that can be accepted by the web services of my mobile app. The app is currently outputting in the format 2013-03-26 17:27:55 on older generation generation devices (iPhone 3GS, 4 and the iOS Simulator), where the 12-hour time appears in the format 5:27 PM in the status bar. This is fine, and it's the format that I need it to be in for the server.

My problem arises when using newer devices (including the iPhone 4S and the iPhone 5) where the 12-hour time appears in the format 5:27 p.m in the status bar. On these devices, the app outputs the in the format 2013-03-26 05:27:55 PM. Here's a summary of the problem:

Web service accepts yyyy-mm-dd HH:MM:ss
iPhone 4 and earlier yyyy-mm-dd HH:MM:ss (correct)
iPhone 4s and later yyyy-mm-dd HH:MM:ss AM/PM (incorrect and rejected)

So, how can I get the outputted date on the 4S and later to be in 24-hour format when 24-hour time is OFF in the User's General Settings?

EDIT:

I'm using the following (NSDate *)getCurrentDate method to try and modify the format of the NSDate object.

NSDate *currentDateAndTime = [[NSDate alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSLog(@"AM Symbol: %@", formatter.AMSymbol);
NSLog(@"PM Symbol: %@", formatter.PMSymbol);

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

NSLog(@"currentDate: %@ currentDateString: %@", date, dateString);

return [formatter dateFromString:[formatter stringFromDate:currentDateAndTime]];
4

1 に答える 1

1

Use a date formatter

- (NSString *)dateStringForWebService:(NSDate *)date
{
    //If you call this often, you should cache the date formatter object
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yy HH:mm:ss"];
    NSString * formattedDate = [dateFormatter stringFromDate:date];
    return formattedDate;
}
于 2013-03-26T18:36:43.787 に答える