2015-07-05 14 views
5

Sto cercando di ottenere solo il tempo e tale formato anche in 24 ore dal seguente stringa:24 ore dalla data di stringa

7/2/2015 2:30:00 PM

Questo è quello che ho provato:

-(NSString*)returnDate:(NSString*)dateString 
{ 

    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; 
    [dateFormatter1 setDateFormat:@"MM/dd/yyyy hh:mm:ss aaa"]; 
    NSDate *date = [dateFormatter1 dateFromString:dateString]; 

    dateString = [date descriptionWithLocale:[NSLocale systemLocale]]; 



    NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone]; 
    NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; 

    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date]; 
    NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date]; 
    NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset; 

    NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date]; 

    NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init]; 
    [dateFormatters setDateFormat:@"HH:mm a"]; 
    [dateFormatters setDateStyle:NSDateFormatterShortStyle]; 
    [dateFormatters setTimeStyle:NSDateFormatterShortStyle]; 
    [dateFormatters setDoesRelativeDateFormatting:YES]; 
    [dateFormatters setTimeZone:[NSTimeZone systemTimeZone]]; 
    dateString = [dateFormatters stringFromDate: destinationDate]; 

    return dateString; 
} 

uscita: 04:30

Questo sta ritornando ora esatta ma nel formato 12 ore. Voglio il tempo nel formato 24 ore.

output desiderato: 16:30

+2

Elimina la "a" dal formato, che richiede am PM. Elimina anche le istruzioni di formattazione ShortStyle e RelativeDate. Vedi: [ICU Formatting Dates and Times] (http://userguide.icu-project.org/formatparse/datetime) – zaph

+1

@zaph: Wao !!! Semplicemente cambiato ciò che hai suggerito. Ha funzionato perfettamente. – Nitish

+0

Vedere la mia risposta, vedere se funziona per voi. – zaph

risposta

4

Non c'è modo per molto codice in questione, provate questo:

NSString *dateString = @"7/2/2015 4:30:00 PM"; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 

[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss aaa"]; 
NSDate *date = [dateFormatter dateFromString:dateString]; 

[dateFormatter setDateFormat:@"HH:mm"]; 
dateString = [dateFormatter stringFromDate: date]; 

NSLog(@"dateString: %@", dateString); 

uscita:

dateString: 16:30

+1

Esattamente quello di cui avevo bisogno. – Nitish

+2

È inoltre necessario utilizzare le impostazioni internazionali speciali di 'en_US_POSIX' per evitare problemi dovuti all'impostazione dell'orario di 24 ore dell'utente sul dispositivo. – rmaddy

+0

@zaph: ho trovato una cosa. Funziona perfettamente quando l'impostazione dell'iPhone è stata impostata su 12 ore, ma quando si passa al formato 24 ore, ottengo dateString come 00:00. Qualche idea ? – Nitish

Problemi correlati