Szukam, aby uzyskać aktualną godzinę i minutę na iPhone użytkownika do wyświetlania w aplikacji, która nie pokazuje pasek stanu. Czy istnieje prosty sposób to zrobić?
Pobieranie aktualnego czasu lokalnego na 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;
Myślę, że należy spróbować. Strefa czasowa jest bardzo ważne.
Zobacz to podobne pytanie na odpowiedź. Trzeba będzie zmienić go do formatu daty.
[[NSDate date] timeIntervalSince1970]; jeśli szukasz do obliczania przedziałów czasowych, jesteś lepiej wyłączyć za pomocą CACurrentMediaTime
double currentTime = CACurrentMediaTime();
CFAbsoluteTimeGetCurrent ()
Absolutny czas w sekundach w stosunku do bezwzględnej dniu odniesienia 1 stycznia 2001 00:00:00 GMT. Wartość dodatnia oznacza datę po dacie odniesienia, wartość ujemna oznacza datę, przed nim. Na przykład, czas bezwzględny -32940326 jest równoznaczne z 16 grudnia 1999 at 17:54:34. Powtarzające wywołania tej funkcji nie gwarantują monotonicznie rosnące wyniki. Czas systemowy może się zmniejszyć ze względu na synchronizację z zewnętrznymi odniesieniami czasu lub z powodu wyraźnej zmiany użytkownika zegara.
Krótszy podejście
NSDate * now = [NSDate date];
timeLabel.text = [NSDateFormatter localizedStringFromDate:now
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterShortStyle];













