Abbin Varghese Abbin Varghese - 3 months ago 9
iOS Question

Convert NSString (eg: "2300") to NSDate (iOS)

I'm trying to convert an

NSString
like this one "2300" to
NSDate
format. (Note: there is no colon after 23).

I get the string from an external web service. I need to display this time in my app in 12hr format.

Thank You :)

Answer

I added here in three types , in which tyope you need choose

Type -1

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HHmm"];
 NSDate *date = [formatter dateFromString:@"2300"];
  [formatter setDateFormat:@"hh:mm"];
NSString *finalDate = [formatter stringFromDate:date];
NSLog(@"finalDate==%@",finalDate);

Type -2

NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:@"HHmm"];
NSDate *date1 = [formatter1 dateFromString:@"2300"];
[formatter1 setDateFormat:@"hhmm"];
NSString *finalDate1 = [formatter1 stringFromDate:date1];
NSLog(@"finalDate1==%@",finalDate1);

Type -3

NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:@"HHmm"];
NSDate *date2 = [formatter1 dateFromString:@"2300"];
[formatter2 setDateFormat:@"hh:mm a"];
NSString *finalDate2 = [formatter2 stringFromDate:date2];
NSLog(@"finalDate2==%@",finalDate2);

your get the output like

enter image description here

Comments