如何在 Cocoa 中获取当前日期 [英] How do I get the current date in Cocoa

查看:29
本文介绍了如何在 Cocoa 中获取当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开始为 iPhone 进行开发,因此我在网上查看不同的教程以及自己尝试一些不同的东西.目前,我正在尝试创建一个倒计时直到午夜.要获得小时数、分钟数和秒数,我执行以下操作(我在某处找到了):

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):

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];

但是,我使用 -dateWithCalendarFormat:timeZone: 的每个地方都会出现以下错误:

However, each place I use -dateWithCalendarFormat:timeZone: I get the following error:

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?

另外,我在不同的地方和不同的时间注意到星号 (*) 位于 NSDate* now 之后或变量 NSDate *now<之前/代码>.两者有什么区别,为什么要使用一个而不是另一个?

Also, I've noticed at different places and at different times the asterisk (*) is located either right after the time NSDate* now or right before the variable NSDate *now. What is the difference in the two and why would you use one versus the other?

推荐答案

您必须使用以下内容:

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];

NSDate* now 和 NSDate *now 之间没有区别,只是喜好问题.从编译器的角度来看,没有任何变化.

There is no difference between NSDate* now and NSDate *now, it's just a matter of preference. From the compiler perspective, nothing changes.

这篇关于如何在 Cocoa 中获取当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆