2015-07-05 12 views
5

Próbuję uzyskać tylko taki format czasu i zbyt w 24 godziny od następujący ciąg:24 godzin od daty ciąg

7/2/2015 2:30:00 PM

ten jest to, co próbowałem:

-(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; 
} 

wyjściowy: 4:30

To jest powrót prawidłowego czasu ale w formacie 12-godzinnym. Chcę mieć czas w formacie 24-godzinnym.

pożądany wynik: 16:30

+2

Usuń "a" z formatu, który żąda am/pm. Usuń również instrukcje formatowania ShortStyle i RelativeDate. Zobacz: [Formatowanie dat i godzin ICU] (http://userguide.icu-project.org/formatparse/datetime) – zaph

+1

@zaph: Wao !!! Po prostu zmień to, co zasugerowałeś. Działało idealnie. – Nitish

+0

Zobacz moją odpowiedź, sprawdź, czy to działa. – zaph

Odpowiedz

4

Jest sposobem dużo kodu w pytaniu, spróbuj tego:

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); 

wyjściowa:

DateString: 16:30

+1

Dokładnie to, czego potrzebowałem. – Nitish

+2

Musisz również użyć specjalnego ustawienia narodowego 'en_US_POSIX', aby uniknąć problemów związanych z 24-godzinnym ustawieniem czasu użytkownika na urządzeniu. – rmaddy

+0

@zaph: Znalazłem jedną rzecz. Działa to dobrze, gdy ustawienie iPhone'a zostało ustawione na 12 godzin, ale gdy zostanie zmienione na format 24-godzinny, otrzymam dateString jako 00:00. Dowolny pomysł ? – Nitish

Powiązane problemy