我希望在用户的iPhone上获取当前的小时和分钟,以便在不显示状态栏的应用中显示.有一个简单的方法吗?
// get current date/time NSDate *today = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; NSString *currentTime = [dateFormatter stringFromDate:today]; [dateFormatter release]; NSLog(@"User's current time in their preference format:%@",currentTime);
-(void)currentTime { //Get current time NSDate* now = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; NSDateComponents *dateComponents = [gregorian components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:now]; NSInteger hour = [dateComponents hour]; NSString *am_OR_pm=@"AM"; if (hour>12) { hour=hour%12; am_OR_pm = @"PM"; } NSInteger minute = [dateComponents minute]; NSInteger second = [dateComponents second]; [gregorian release]; NSLog(@"Current Time %@",[NSString stringWithFormat:@"%02ld:%02ld:%02ld %@", (long)hour, (long)minute, (long)second,am_OR_pm]); }
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; [dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; NSString *currentTime = [dateFormatter stringFromDate:[NSDate date]] [dateFormatter release]; dateFormatter = nil;
我想你应该试试这个.时区非常重要.
请参阅此类似问题以获得答案.您必须将其更改为您的日期格式.
[[NSDate date] timeIntervalSince1970];
如果您要计算时间间隔,最好使用CACurrentMediaTime
double currentTime = CACurrentMediaTime();