我得到了像 07:14 Am/Pm 这样的时间格式,我需要在 NSDateComponent 中像 19:14 那样转换

I am getting the time format like 07:14 Am/Pm that I required to convert like 19:14 in NSDateComponent

我想在设置时间时获得本地通知,所以在 timepickker 中,我得到了像 07:14 Am/Pm 这样的时间格式,我需要像 19:14 这样转换,这样我就可以设置像

这样的值

我想将 07 转换为 19 如何将值放入 datecomponet..

 //getting time format 07:14 Am/Pm
     NSString * time1 = Timepicker.text;
                NSArray *array = [time1 componentsSeparatedByString:@":"];



            [datecomponet setHour:19];
            [datecomponet setMinute:38];



[dateformater setDateFormat:@"hh:mm a"];
        self.Timepicker.text= [NSString stringWithFormat:@"%@",[dateformater stringFromDate:datepicker.date]];


/// This is local notification code

NSCalendar * gregcalender = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    [gregcalender setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"IST"]];

    NSDateComponents *datecomponet = [gregcalender components:NSCalendarUnitYear|NSCalendarUnitMonth |  NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:date];

//    [datecomponet setYear:2017];
//    [datecomponet setMonth:12];
//    [datecomponet setDay:16];
//    [datecomponet setHour:18];
//    [datecomponet setMinute:38];

    NSInteger year = [datecomponet year];
    NSInteger month = [datecomponet month];
    NSInteger day = [datecomponet day];


    NSString * time1 = Timepicker.text;
//    NSInteger hour = [datecomponet hour];
//    NSInteger min = [datecomponet minute];
    //NSString *testString= @"It's a rainy day";
    NSArray *array = [time1 componentsSeparatedByString:@":"];

        [datecomponet setHour:18];
        [datecomponet setMinute:38];


    UIDatePicker * dd = [[UIDatePicker alloc]init];
    [dd setDate:[gregcalender dateFromComponents:datecomponet]];

    NSLog(@"======>NSNotification method tab<=====");

尝试在操场上这样做:

Swift 例子:

let stringDate = "16:00:00"

let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "HH:mm:ss"
let date1 = dateFormatter1.date(from: stringDate)
print(date1!)

let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "hh:mm a"
print(dateFormatter2.string(from: date1!))
print(dateFormatter1.string(from: date1!))

Objective-C 示例:(粘贴到任何 viewDidLoad

NSString *stringDate = @"16:00:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSDate *date1 = [dateFormatter dateFromString:stringDate];
NSLog(@"%@", date1);

NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:@"hh:mm a"];
NSLog(@"%@", [dateFormatter2 stringFromDate:date1]);
NSLog(@"%@", [dateFormatter stringFromDate:date1]);

结果:

  • 2000-01-01 14:00:00 +0000 / 1 月 1 日星期六 16:00:00 2000(包括我的时区)
  • 04:00 下午
  • 16:00:00

注: 如果你想获得:

  • 上午 12 点,下午 5 点然后使用 "hh mm a"
  • 00, 17 然后使用 "HH mm a"