Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

24 hour time from date string

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

like image 390
Nitish Avatar asked Sep 27 '22 10:09

Nitish


1 Answers

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

like image 170
zaph Avatar answered Oct 13 '22 12:10

zaph