0

I have an NSDate Object which is in 12 hour format like 2014-09-16 04:40:05 pm +0000.

I want to convert this into 24 hour format and want to get back an NSDate object like 2014-09-16 16:40:05 +0000.

Can some one guide me in doing that.

So i want some method like :

-(NSDate *) get24HourFormat:(NSDate *) date{

  return date object;
} 
Rakesh
  • 3,370
  • 2
  • 23
  • 41
Abdul Samad
  • 5,748
  • 17
  • 56
  • 70

3 Answers3

5

Simple use this:

 NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
 dateformate.dateFormat = @"HH:mm a"; // Date formater
 NSString *timeString = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
 NSLog(@"timeString :%@",timeString);

Logic: Simply convert date format hh:mm to HH:mm

Soumya Ranjan
  • 4,817
  • 2
  • 26
  • 51
2

There seems to be a deep misunderstanding here what NSDate is and does.

An NSDate object is a point in time in UTC. It doesn't have a time zone. It doesn't have a format. It has nothing. You can't change its format, it doesn't even make any sense.

What you can do is to use an NSDateFormatter to convert the NSDate to a string. By default, NSDateFormatter uses your local time zone, which means for most people that the result will be different from the result that NSLog would show for an NSDate. In the NSDateFormatter, you can use whatever settings you want.

Usually you would respect how the user set up his date formatting and not change it for anything that is visible to the user. As a user, if I had set up my device to show days in 12 hour format, I'd be very annoyed if your application worked differently.

Darshan Kunjadiya
  • 3,323
  • 1
  • 29
  • 31
gnasher729
  • 51,477
  • 5
  • 75
  • 98
-1

try this..

 -(NSString *)changeformate_string24hr:(NSString *)date
{

    NSDateFormatter* df = [[NSDateFormatter alloc]init];

    [df setTimeZone:[NSTimeZone systemTimeZone]];

    [df setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];

    NSDate* wakeTime = [df dateFromString:date];

    [df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];


    return [df stringFromDate:wakeTime];

}

-(NSString *)changeformate_string12hr:(NSString *)date
{

    NSDateFormatter* df = [[NSDateFormatter alloc]init];

    [df setTimeZone:[NSTimeZone systemTimeZone]];

    [df setDateFormat:@"MM/dd/yyyy HH:mm:ss"];

    NSDate* wakeTime = [df dateFromString:date];

    [df setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];

    return [df stringFromDate:wakeTime];

}
hmdeep
  • 2,910
  • 3
  • 14
  • 22