user4817719
user4817719

Reputation:

How we get date in 12 hour format

I want if user select 24 hour from setting on my string they get time in 12 hour format. I am using this code. It does not show the proper time.

timePicker.datePickerMode=UIDatePickerModeTime;
[timePicker setDate:[NSDate date]];
[timePicker addTarget:self action:@selector(updateTextFieldd:) forControlEvents:UIControlEventValueChanged];


NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"h:mm:a"];
theTime = [dateFormat stringFromDate:timePicker.date];
NSLog(@"%@",theTime);

//    NSDateFormatter *DateFormatters=[[NSDateFormatter alloc] init];  
//    [DateFormatters setDateFormat:@"a"];

if (is24h ==YES) {
    NSArray *seprates=[theTime componentsSeparatedByString:@":"];

    NSString *min = [seprates objectAtIndex:1];
    NSLog(@"%@",min);
    NSString  *hour=[seprates objectAtIndex:0];
    int hours=[hour intValue];
    NSLog(@"%d",hours);

    if (hours==12 &&[min isEqualToString:@"00"]) {

    }
    else
    {
        if (hours>=12) {
            hours=hours-12;
            period=@"PM";
        }
        else
        {
            if (hours==12) {
                hours=hours-11;
                period=@"PM";
            }
            else if (hours>12)
            {
                hours=hours-12;
                period=@"PM";
            }
            else
            {
                period=@"AM";
            }
       }
    }

    if (hours ==0) {
         theTime=[NSString stringWithFormat:@"00:%@",min];
    }
    else
    {
         theTime=[NSString stringWithFormat:@"%d:%@",hours,min];
    }

Upvotes: 1

Views: 431

Answers (3)

vadian
vadian

Reputation: 285082

If you want to force the date to be displayed in 12 hour format with AM/PM, set the locale to en_US.

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"hh:mm a"];
  dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
  NSString *theTime = [dateFormatter stringFromDate: [NSDate date]];
  NSLog(@"%@",theTime);

Upvotes: 2

Amit Shelgaonkar
Amit Shelgaonkar

Reputation: 487

Try this

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 dateFormatter.dateFormat = @"HH:mm";
 NSDate *date = [dateFormatter dateFromString:@"23:50"];//suppose take time 23:50

 dateFormatter.dateFormat = @"hh:mm a";
 NSString *DateString = [dateFormatter stringFromDate:date];

Upvotes: 0

Chetan Prajapati
Chetan Prajapati

Reputation: 2297

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setDateFormat:@"hh:mm a"];

Set your full date with this formatter. I have just given hint.

Upvotes: 2

Related Questions