I am trying to get just the time and that too in 24 hour format from following string :
7/2/2015 2:30:00 PM
This is what I have 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;
}
Output : 4:30
This is returning correct time but in 12 hour format. I want the time in 24 hour format.
Desired output : 16:30
There is way to much code in the question, try this:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With