24 hour time from date string

I am trying to get only time and this is also in 24 hour format from the following line:

7/2/2015 2:30:00 PM

Here is what I tried:

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

Exit: 4:30

This returns the correct time, but in a 12 hour format. I want time in a 24 hour format.

Desired conclusion: 16:30

+5
source share
1 answer

There is a lot of code in the question, try the following:

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

Output:

dateString: 16:30

+4
source

All Articles