如何在[NSDate日期]当天00:00获得NSDate? [英] How to get NSDate for 00:00 on the day of [NSDate date]?

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

问题描述

我需要从[NSDate日期] 00:00(当天开始)获取NSDate对象,假设当前是上午11:30(由[NSDate日期]返回),在01/06/2012 ,现在我需要在01/06/2012 00:00 am获得NSDate。

I need to get an NSDate object for 00:00(beginning of the day) from [NSDate date], let's say if currently it is 11:30am(returned by [NSDate date]), on 01/06/2012, now I need to have an NSDate for 00:00am on 01/06/2012.

我没试过这个,但我的想法是:

I haven't tried this, but what is in my mind is:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSDate *morningStart = [calendar dateFromComponents:components];

所以我首先得到当前日期(比如说是01/06/2012),然后构造一个NSDateComponent对于日期,然后我将小时/分钟/秒设置为0并且不应更改年/月/日(即01/06/2012)然后我为此组件设置创建NSDate并且我可以获得日期00:00:00 01/06/2012?

So I first get current date(say it is 01/06/2012), and construct a NSDateComponent for the date, then I set hour/minute/second to 0 and the year/month/day should not be changed(ie. 01/06/2012) then I create an NSDate for this component setting and can I get a date of 00:00:00 01/06/2012?

推荐答案

你做的是正确的,但当你在NSLog morningStart时,日期将是以GMT时区显示

What you doing is correct, but when you NSLog morningStart the date will be displayed in GMT time zone

如果您想确保日期正确,请将其转换为NSString

If you wanna make sure that the date is correct, convert it to NSString

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 [formatter setDateFormat:@"yyyy-MMM-dd HH:mm:ss"];
 NSString *strFromDate = [formatter stringFromDate:morningStart]; // this will return 2012-Jun-21 00:00:00

这篇关于如何在[NSDate日期]当天00:00获得NSDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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