NSDate 获取年/月/日
在没有其他信息的情况下,如何获取 NSDate
对象的年/月/日?我意识到我可能可以用类似的东西来做到这一点:
NSCalendar *cal = [[NSCalendar alloc] init];
NSDateComponents *components = [cal components:0 fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];
但这对于像获取 NSDate 的年/月/日这样简单的事情来说似乎是一大堆麻烦。还有其他解决办法吗?
How can I get the year/month/day of a NSDate
object, given no other information? I realize that I could probably do this with something similar to this:
NSCalendar *cal = [[NSCalendar alloc] init];
NSDateComponents *components = [cal components:0 fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];
But that seems to be a whole lot of hassle for something as simple as getting a NSDate
's year/month/day. Is there any other solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
我写这个答案是因为它是唯一一种不会从
NSDateComponent
变量返回选项和/或强制解开这些变量的方法(也适用于 Swift 3)。Swift 3
Swift 2
Bonus Swift 3 趣味版
I'm writing this answer because it's the only approach that doesn't give you optionals back from
NSDateComponent
variables and/or force unwrapping those variables (also for Swift 3).Swift 3
Swift 2
Bonus Swift 3 fun version
iOS 8 中的新功能
ObjC
Swift
New In iOS 8
ObjC
Swift
从 iOS 8.0(和 OS X 10)开始,您可以使用 component 方法来简化获取单个日期组件的过程,如下所示:
应该让事情变得更简单,希望这可以有效实现。
As of iOS 8.0 (and OS X 10) you can use the component method to simplify getting a single date component like so:
Should make things simpler and hopefully this is implemented efficiently.
如果您的目标是 iOS 8+,您可以使用新的
NSCalendar
便捷方法以更简洁的格式实现此目的。首先创建一个
NSCalendar
并使用所需的任何NSDate
。您可以通过
component:fromDate:
单独提取组件,或者更简洁地,通过
getEra:year:month:day:fromDate:
使用NSInteger
指针>有关更多信息和示例,请查看iOS 8 中的 NSDate 操作变得轻松。免责声明,我写了这篇文章。
If you are targeting iOS 8+ you can use the new
NSCalendar
convenience methods to achieve this in a more terse format.First create an
NSCalendar
and use whateverNSDate
is required.You could extract components individually via
component:fromDate:
Or, even more succinctly, use
NSInteger
pointers viagetEra:year:month:day:fromDate:
For more information and examples check out NSDate Manipulation Made Easy in iOS 8. Disclaimer, I wrote the post.
如果您希望从 NSDate 获取单独的 NSDateComponents,您肯定需要 Itai Ferber 建议的解决方案。但是如果你想从 NSDate 直接转换为 NSString,你可以使用 NSDateFormatter。
If you wish to get the individual NSDateComponents from NSDate, you would definitely need the solution suggested by Itai Ferber. But if you want to go from NSDate directly to an NSString, you can use NSDateFormatter.
请尝试以下操作:
Try the following:
这是 Swift 中的解决方案:
Here's the solution in Swift:
试试这个。 。 。
代码片段:
它给出当前的年、月、日
Try this . . .
Code snippet:
It gives current year, month, date
Swift
更简单的方法来获取日期的任何元素作为可选字符串。
Swift
Easier way to get any elements of date as an optional String.
Swift 2.x
您可以将其用作
输出
Swift 2.x
You can use it as
Output
我这样做......
i do in this way ....
要获得人类可读的字符串(日、月、年),您可以这样做:
To get human readable string (day, month, year), you may do:
因为这显然是我最受欢迎的答案,所以我将尝试编辑它以包含更多信息。
尽管有它的名字,
NSDate
本身只是标记机器时间中的一个点,而不是日期。NSDate
指定的时间点与年、月或日之间没有关联。为此,您必须参考日历。任何给定的时间点都会根据您查看的日历返回不同的日期信息(例如,公历和犹太历中的日期不相同),而公历是世界上使用最广泛的日历。 world - 我假设 - 我们有点偏向于NSDate
应该始终使用它。幸运的是,NSDate 的两党合作程度要高得多。正如您提到的,获取日期和时间必须通过
NSCalendar
传递,但有一种更简单的方法:生成一个包含日、月的
NSDateComponents
对象,以及当前系统日历中的年份。 (注意:这不一定是当前用户指定的日历,而只是默认的系统日历。)当然,如果您使用不同的日历或日期,你可以轻松改变这一点。可用日历和日历单位的列表可以在
NSCalendar
类参考。有关NSDateComponents
的更多信息可以在NSDateComponents
类参考。作为参考,从
NSDateComponents
访问各个组件相当简单:您只需要注意:
NSDateComponents
不会包含您要求的任何字段的有效信息,除非您生成他们与该有效信息(即请求 NSCalendar 提供该信息与 NSCalendarUnit s)。NSDateComponents
本身不包含任何参考信息 - 它们只是保存数字供您访问的简单结构。例如,如果您还想从NSDateComponents
中获取一个时代,则必须使用NSCalendarUnitEra
从NSCalendar
提供生成器方法> 旗帜。Because this is apparently my most popular answer, I'll try to edit it to contain a little bit more information.
Despite its name,
NSDate
in and of itself simply marks a point in machine time, not a date. There's no correlation between the point in time specified by anNSDate
and a year, month, or day. For that, you have to refer to a calendar. Any given point in time will return different date information based on what calendar you're looking at (dates are not the same in both the Gregorian and Jewish calendars, for instance), and while the Gregorian calendar is the most widely used calendar in the world - I'm assuming - we're a little biased thatNSDate
should always use it.NSDate
, luckily, is far more bipartisan.Getting date and time is going to have to pass through
NSCalendar
, as you mentioned, but there's a simpler way to do it:That generates an
NSDateComponents
object containing the day, month, and year from the current system calendar for the current day. (Note: this isn't necessarily the current user-specified calendar, just the default system one.)Of course, if you're using a different calendar or date, you can easily change that. A list of available calendars and calendar units can be found in the
NSCalendar
Class Reference. More information aboutNSDateComponents
can be found in theNSDateComponents
Class Reference.For reference, accessing individual components from the
NSDateComponents
is rather easy:You just have to be mindful:
NSDateComponents
won't contain valid information for any fields you ask for unless you generated them with that valid information (i.e. requestNSCalendar
to provide that information withNSCalendarUnit
s).NSDateComponents
contain no reference information in and of themselves - they're just simple structures that hold numbers for you to access. If you want to also get an era, for instance, out ofNSDateComponents
, you'll have to feed the generator method fromNSCalendar
with theNSCalendarUnitEra
flag.您可以使用 NSDateFormatter 获取 NSDate 的单独组件:
如果您希望获取月份数字而不是缩写,请使用“MM”。如果您想获取整数,请使用
[myDayString intValue];
You can get separate component of a NSDate using NSDateFormatter:
If you wish to get month's number instead of abbreviation, use "MM". If you wish to get integers, use
[myDayString intValue];
只是为了重写 Itai 的优秀(并且有效!)代码,下面是示例帮助程序类的样子,用于返回给定 NSDate 变量的 year 值。
正如您所看到的,修改此代码以获取月份或日期非常容易。
(我不敢相信我们必须在 2013 年编写这样的我们自己的基本 iOS 日期函数......)
另一件事:永远不要使用 <<和>比较两个 NSDate 值。
XCode 会很乐意接受这样的代码(没有任何错误或警告),但它的结果是彩票。您必须使用“比较”函数来比较 NSDate:
Just to reword Itai's excellent (and working!) code, here's what a sample helper class would look like, to return the year value of a given NSDate variable.
As you can see, it's easy enough to modify this code to get the month or day.
(I can't believe we're having to write our own basic iOS date functions like this, in 2013...)
One other thing: don't ever use < and > to compare two NSDate values.
XCode will happily accept such code (without any errors or warnings), but its results are a lottery. You must use the "compare" function to compare NSDates:
在斯威夫特 2.0 中:
In Swift 2.0: