如何查看一周中的哪一天(即星期二,星期五?)并比较两个NSDates? [英] How to check what day of the week it is (i.e. Tues, Fri?) and compare two NSDates?

查看:99
本文介绍了如何查看一周中的哪一天(即星期二,星期五?)并比较两个NSDates?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做两件事:


  1. 检查一周是否已过去(基于星期几)

  2. 检查一天是否过去了(根据日期)

我是不知道解决这个问题的最佳方法是什么,因为在比较两个NSDates时(一个在2009年1月1日21:30和另一个在2009年1月1日凌晨1点半)我不能只看24小时已经过去了,因为在这种情况下它还没有。我可以通过从NSDate获取日期1/1/09来解决这个问题,但我不确定如何根据我看到的文档和谷歌链接来做到这一点。

I'm not sure what the best way to solve this is, since when comparing two NSDates (one at 1/1/09 at 21:30 and another at 1/2/09 at 00:30) I can't just see if 24 hours has gone by since in this case it hasn't. I can solve this by just getting the date 1/1/09 from the NSDate, but I'm unsure how to do this based on the documentation and google links that I saw.

对于另一个问题,我不知道如何知道星期几的哪一天。我想如果1/1/09是星期二,星期一等等......是否有任何图书馆让你计算这个?这显然需要考虑闰年和其他一些东西...也许有一个Objective-c库?

For the other issue, I don't know how to know what day of the week it is given a date. I'd like to if 1/1/09 is a Tuesday, Monday, etc... Is there any library that let's you calculate this? This obviously needs to take into account leap years and a tons of other stuff... Maybe there's an objective-c library for this?

感谢您的帮助!

推荐答案

您可以使用 NSDateComponents

unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:units fromDate:date];

然后您可以访问日期的各个部分,如下所示:

then you can access individual parts of the date like this:

[components year];
[components month];
[components day];

或者,您可以使用 NSCalendar构建新的NSDate对象 dateFromComponents 方法,并比较两个 NSDate 对象。

Or, you can construct a new NSDate object using NSCalendar's dateFromComponents method, and compare the two NSDate objects.

这篇关于如何查看一周中的哪一天(即星期二,星期五?)并比较两个NSDates?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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