2

我有这段代码,但它只显示 hh:mm。我想显示 yyyy、mm 和 dd。我想在时间上增加 1 小时,因为它会显示某件事什么时候会被激活。

有人能告诉我这是怎么做到的吗?:)

-(IBAction)timeStampPressed:(id)sender{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle: NSDateFormatterShortStyle];


    NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];
    NSLog(@"time: %@",currentTime);
}
4

2 回答 2

2

您可以使用以下代码

-(IBAction)timeStampPressed:(id)sender{

     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setTimeStyle: NSDateFormatterShortStyle];
     dateFormatter.dateFormat = @"dd-MM-yyyy hh:mm a";

     NSString *currentTime = [dateFormatter stringFromDate: [NSDate date]];
     NSLog(@"time: %@",currentTime);
}
于 2013-09-10T12:36:29.310 回答
0

您也可以通过 NSCalendar 实现它:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:[NSDate date]];

NSString *result = [NSString stringWithFormat:@"%d %02d %02d:%02d", [dateComponents year], [dateComponents day], [dateComponents hour] + 1, [dateComponents minute]];
于 2013-09-10T12:43:56.510 回答