Jak uzyskać aktualną datę w Cocoa
Zaczynam pracę nad iPhonem i w związku z tym patrzę na różne samouczki online, a także sam próbuję różnych rzeczy. Obecnie próbuję stworzyć odliczanie do północy. Aby uzyskać liczbę godzin, minut i sekund, wykonuję następujące czynności (które gdzieś znalazłem):
NSDate* now = [NSDate date];
int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay];
int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour];
int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute];
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec];
Jednak w każdym miejscu używam -dateWithCalendarFormat:timeZone:
pojawia się następujący błąd:
warning: 'NSDate' may not respond to '-dateWithCalendarFormat:timeZone:'
(Messages without a matching method signature will be assumed to return 'id' and accept '...' as arguments.)
warning: no '-hourOfDay' method found
error: invalid operands to binary - (have 'int' and 'id')
To wygląda na coś bardzo prostego. Co przegapiłem?
Również, mam gwiazdka (*) znajduje się tuż po czasie NSDate* now
lub tuż przed zmienną NSDate *now
. Jaka jest różnica w tych dwóch i dlaczego miałbyś używać jednego kontra drugiego?
14 answers
Należy użyć:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:yourDateHere];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
Nie ma różnicy między NSDate* now a nsdate * now, to tylko kwestia preferencji. Z punktu widzenia kompilatora nic się nie zmienia.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-01 17:37:10
Masz problemy z iOS 4.2? Użyj tego kodu:
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd.MM.YY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"%@",dateString);
-->20.01.2011 10:36:02
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-20 09:39:10
Możesz również użyć:
CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02.0f", currentDate.hour, currentDate.minute, currentDate.second];
CFRelease(currentDate); // Don't forget this! VERY important
Myślę, że ma to następujące zalety:
-
Brak bezpośredniej alokacji pamięci.
- Seconds jest liczbą podwójną zamiast liczby całkowitej.
- żadnych wiadomości. Szybciej.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-13 10:17:22
// możesz pobrać aktualną datę/czas za pomocą następującego kodu:
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
formatter.timeZone = destinationTimeZone;
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setDateFormat:@"MM/dd/yyyy hh:mma"];
NSString* dateString = [formatter stringFromDate:date];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-27 12:47:33
Zastąp to:
NSDate* now = [NSDate date];
int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay];
int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour];
int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute];
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec];
Z tym:
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
[gregorian release];
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, second];
Zauważyłem również, że w różnych miejscach i o różnych porach gwiazdka (
*
) znajduje się albo zaraz po czasieNSDate* now
, albo tuż przed zmiennąNSDate *now
. Jaka jest różnica w tych dwóch i dlaczego miałbyś używać jednego kontra drugiego?
Kompilator ma to gdzieś, ale umieszczenie gwiazdki przed spacją może być mylące. Oto mój przykład:
int* a, b;
Jaki jest typ b
?
Jeśli zgadłeś int *
, mylisz się. To tylko int
.
Drugi sposób sprawia, że jest to nieco jaśniejsze, trzymając * obok zmiennej, do której należy:
int *a, b;
Oczywiście istnieją dwa sposoby, które są jeszcze jaśniejsze:
int b, *a;
int *a;
int b;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-02 02:35:41
Musisz zrobić coś w następujący sposób:
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSLog(@"%d", [components hour]);
I tak dalej.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-01 17:45:58
Oto inny sposób:
NSDate *now = [NSDate date];
//maybe not 100% approved, but it works in English. You could localize if necessary
NSDate *midnight = [NSDate dateWithNaturalLanguageString:@"midnight tomorrow"];
//num of seconds between mid and now
NSTimeInterval timeInt = [midnight timeIntervalSinceDate:now];
int hours = (int) timeInt/3600;
int minutes = ((int) timeInt % 3600) / 60;
int seconds = (int) timeInt % 60;
Tracisz precyzję subsekundową z obsadą NSTimeInterval do int, ale to nie powinno mieć znaczenia.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-01 19:36:58
NSDate* now
i NSDate *now
są tym samym: wskaźnikiem do obiektu NSDate.
Prawdopodobnie chcesz użyć descriptionWithCalendarFormat:timeZone:locale: zamiast dateWithCalendarFormat: - Ten ostatni zwraca NSCalendarDate, który według dokumentów ma być w pewnym momencie przestarzały.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-01 21:19:50
Oryginalny plakat - sposób, w jaki określasz sekundy do północy, nie zadziała w dniu, w którym zaczyna się lub kończy czas letni. Oto fragment kodu, który pokazuje, jak to zrobić... Będzie to w ciągu kilku sekund( NSTimeInterval); możesz zrobić podział / moduł / etc, aby dostać się do czego potrzebujesz.
NSDateComponents *dc = [[NSCalendar currentCalendar] components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:[NSDate date]];
[dc setDay:dc.day + 1];
NSDate *midnightDate = [[NSCalendar currentCalendar] dateFromComponents:dc];
NSLog(@"Now: %@, Tonight Midnight: %@, Hours until midnight: %.1f", [NSDate date], midnightDate, [midnightDate timeIntervalSinceDate:[NSDate date]] / 60.0 / 60.0);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-07 11:40:32
Nie ma różnicy w lokalizacji gwiazdki (w C, na której opiera się Obj-C, nie ma znaczenia). Jest to czysto preferencja (styl).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-01 17:32:45
Trochę mi zajęło zlokalizowanie, dlaczego przykładowa aplikacja działa, ale moja nie.
Biblioteka (Fundacja.Framework), do którego autor odnosi się to biblioteka systemowa (z systemu operacyjnego), w której iphone sdk (używam 3.0) nie jest już obsługiwany.
Dlatego przykładowa aplikacja (z about.com, http://www.appsamuck.com/day1.html ) działa, ale nasze nie.
CFGregorianDate currentDate = CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem());
countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%2.0f", currentDate.hour, currentDate.minute, currentDate.second];
Mark miał rację Ten kod jest znacznie bardziej wydajny do zarządzania datami godziny min i sekundy. Ale zapomniał @ na początku deklaracji łańcuchowej formatu.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-08 15:55:42
+ (NSString *)displayCurrentTimeWithAMPM
{
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"h:mm aa"];
NSString *dateTime = [NSString stringWithFormat:@"%@",[outputFormatter stringFromDate:[NSDate date]]];
return dateTime;
}
Return 3: 33 AM
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-17 19:32:40