iOS:显示上午/下午的时间

时间:2013-08-22 08:41:48

标签: ios objective-c datetime

我是客观的新手。我希望做到以下几点: 将24小时格式转换为12小时,然后将+2添加到小时,并显示如下:下午4:00 我得到了12小时的格式,但是在加上+2之后,时间总是显示为“am”,即使它是下午4点,它显示为凌晨4点。以下是我的代码:

NSDate *now = [NSDate date];
NSDateFormatter *timeFormatter=[[NSDateFormatter alloc]init];
timeFormatter.dateFormat=@"hh:00 a";
NSString  *currentHour=[timeFormatter stringFromDate:now ];
lblcurrentHour.text=[NSString stringWithFormat:@"%@",currentHour];
NSLog(@"%@",currentHour);

int hour=[[timeFormatter stringFromDate:now]intValue];

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
dateFormatter1.dateFormat = @"HH:mm";
NSDate *date1 = [dateFormatter1 dateFromString:[NSString stringWithFormat:@"%02d:00",hour+=3]];

dateFormatter1.dateFormat = @"hh:mm a";
lblnextHour.text = [dateFormatter1 stringFromDate:date1]; // prints 4:00 am not pm

我该如何解决这个问题?我哪里出错?

2 个答案:

答案 0 :(得分:2)

如果我正确理解您的要求,您需要获取当前时间并将分钟显示为:00,锚定到当前小时。然后你想添加两个小时并显示那个时间。以下代码将04:00 AM和06:00 AM打印到控制台(本地时间为0421。)

对于日历计算,我会避免在计算两小时后的时间时使用NSDateFormatter。有太多方法可以误入歧途。例如,当现在时间是2300时会发生什么?

关于Cocoa中日历计算的一个很好的参考是here

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        //  use gregorian calendar for calendrical calculations
        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

        //  get current date
        NSDate *date = [NSDate date];
        NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
        units |= NSHourCalendarUnit | NSMinuteCalendarUnit;
        NSDateComponents *currentComponents = [gregorian components:units fromDate:date];

        //  change the minutes to 0
        currentComponents.minute = 0;
        date = [gregorian dateFromComponents:currentComponents];

        //  format and display the time
        NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
        timeFormatter.dateFormat = @"hh:mm a";
        NSString *currentTimeString = [timeFormatter stringFromDate:date];
        NSLog(@"Current hour = %@",currentTimeString);

        //  add two hours
        NSDateComponents *incrementalComponents = [[NSDateComponents alloc] init];
        incrementalComponents.hour = 2;
        NSDate *twoHoursLater = [gregorian dateByAddingComponents:incrementalComponents toDate:date options:0];

        //  format and display new time
        NSString *twoHoursLaterStr = [timeFormatter stringFromDate:twoHoursLater];
        NSLog(@"Two hours later = %@",twoHoursLaterStr);
    }
    return 0;
}

答案 1 :(得分:1)

试试这个:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm:ss a"];
NSLog(@"Today's Date and Time: %@", [formatter stringFromDate:[NSDate date]]);

输出:

  

今天的日期和时间:02:43:33 PM