objective-c 如何在可可中获取当前日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1070354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the current date in Cocoa
提问by Jason
I'm getting started developing for the iPhone and as such I am looking at different tutorials online as well as trying some different things out myself. Currently, I'm trying to create a countdown until midnight. To get the number of hour, minutes, and seconds, I do the following (which I found somewhere):
我开始为 iPhone 进行开发,因此我在网上查看不同的教程,并自己尝试一些不同的东西。目前,我正在尝试创建一个倒计时直到午夜。要获得小时数、分钟数和秒数,我执行以下操作(我在某处找到的):
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];
However, each place I use -dateWithCalendarFormat:timeZone:I get the following error:
但是,我使用的每个地方-dateWithCalendarFormat:timeZone:都会出现以下错误:
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')
This seems like something very simple. What am I missing?
这似乎是一件非常简单的事情。我错过了什么?
Also, I've noticed at different places and at different times the asterisk (*) is located either right after the time NSDate* nowor right before the variable NSDate *now. What is the difference in the two and why would you use one versus the other?
另外,我在不同的地方和不同的时间注意到星号 (*) 位于时间之后NSDate* now或变量之前NSDate *now。两者有什么区别,为什么要使用一个而不是另一个?
采纳答案by Massimo Cafaro
You must use the following:
您必须使用以下内容:
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];
There is no difference between NSDate* now and NSDate *now, it's just a matter of preference. From the compiler perspective, nothing changes.
NSDate* now 和 NSDate *now 之间没有区别,这只是偏好问题。从编译器的角度来看,没有任何变化。
回答by Hover
You have problems with iOS 4.2? Use this Code:
你有 iOS 4.2 的问题吗?使用此代码:
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
-->20.01.2011 10:36:02
回答by Mark
You can also use:
您还可以使用:
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
I think this has the following advantages:
我认为这有以下优点:
- No direct memory allocation.
- Seconds is a double instead of an integer.
- No message calls.
- Faster.
- 没有直接的内存分配。
- Seconds 是双精度而不是整数。
- 没有消息呼叫。
- 快点。
回答by Hemant Sharma
// you can get current date/time with the following code:
// 您可以使用以下代码获取当前日期/时间:
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];
回答by Hemant Sharma
Replace this:
替换这个:
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];
With this:
有了这个:
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];
回答by Peter Hosey
Also, I've noticed at different places and at different times the asterisk (
*) is located either right after the timeNSDate* nowor right before the variableNSDate *now. What is the difference in the two and why would you use one versus the other?
另外,我在不同的地方和不同的时间注意到星号 (
*) 位于时间之后NSDate* now或变量之前NSDate *now。两者有什么区别,为什么要使用一个而不是另一个?
The compiler doesn't care, but putting the asterisk before the space can be misleading. Here's my example:
编译器不在乎,但将星号放在空格之前可能会产生误导。这是我的例子:
int* a, b;
What is the type of b?
的类型是b什么?
If you guessed int *, you're wrong. It's just int.
如果你猜到了int *,那你就错了。这只是int。
The other way makes this slightly clearer by keeping the * next to the variable it belongs to:
另一种方法是通过将 * 放在它所属的变量旁边来稍微清楚一点:
int *a, b;
Of course, there are two ways that are even clearer than that:
当然,还有两种方式比这更清楚:
int b, *a;
int *a;
int b;
回答by Gregory Higley
You need to do something along the lines of the following:
您需要按照以下方式做一些事情:
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSLog(@"%d", [components hour]);
And so on.
等等。
回答by Jeff Hellman
Here's another way:
这是另一种方式:
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;
You lose subsecond precision with the cast of the NSTimeInterval to an int, but that shouldn't matter.
将 NSTimeInterval 转换为 int 会丢失亚秒级精度,但这无关紧要。
回答by John
NSDate* nowand NSDate *noware the same thing: a pointer to an NSDate object.
NSDate* now并且NSDate *now是同一件事:指向 NSDate 对象的指针。
You probably want to use descriptionWithCalendarFormat:timeZone:locale:rather than dateWithCalendarFormat:— the latter returns an NSCalendarDate, which the docs say is scheduled to be deprecated at some point.
您可能想要使用descriptionWithCalendarFormat:timeZone:locale:而不是dateWithCalendarFormat:— 后者返回一个 NSCalendarDate,文档说它计划在某个时候被弃用。
回答by James Boutcher
Original poster - the way you're determining seconds until midnight won't work on a day when daylight savings starts or ends. Here's a chunk of code which shows how to do it... It'll be in number of seconds (an NSTimeInterval); you can do the division/modulus/etc to get down to whatever you need.
原始海报 - 您确定午夜之前的秒数的方式在夏令时开始或结束的那一天不起作用。这是一段代码,展示了如何做到这一点......它将以秒为单位(NSTimeInterval);你可以做除法/模数/等来得到你需要的任何东西。
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);

