无法在12小时内添加ios

时间:2017-05-31 11:32:47

标签: ios objective-c nsdate nsdateformatter

我是iOS新手,

如果其中包含12,我想将PM小时添加到我的NSString。

我试过这段代码,但没有成功

NSString *str = @"1/1/1900 3:00:00 PM"
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy hh:mm:ss A"];

NSDate *date1 = [formatter dateFromString:str];
NSLog(@"date1 : %@", date1);

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

请帮忙

2 个答案:

答案 0 :(得分:0)

你很亲密,只犯了两个小错误。首先,A不是有效的日期格式说明符,它应该是a。其次,要将12小时格式转换为24小时格式,您需要使用HH代替hh作为第二格式化程序。

我修复了代码,运行测试并告诉我。

NSString *str = @"1/1/1900 3:00:00 PM";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// Need lowercase `a`, A is not a valid format
[formatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
NSDate *date1 = [formatter dateFromString:str];
NSLog(@"date1 : %@", date1);

NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
// If you specify the hour to be HH, it will convert the date automaticly to in 24 hour format
[formatter1 setDateFormat:@"HH:mm"];
NSLog(@"Current Date: %@", [formatter1 stringFromDate:date1]);

答案 1 :(得分:-2)

试试这个 !!!

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"HH.mm"];
            NSString *strCurrentTime = [dateFormatter stringFromDate:[NSDate date]];

            NSLog(@"Check float value: %.2f",[strCurrentTime floatValue]);
            if ([strCurrentTime floatValue] >= 19.00 || [strCurrentTime floatValue]  <= 7.00)
            {

             NSLog(@"It's night time");

            }else
            {
                NSLog(@"It's day time");
            }