Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get NSDate for 00:00 on the day of [NSDate date]?

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

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?

like image 420
hzxu Avatar asked Jun 21 '12 07:06

hzxu


1 Answers

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

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
like image 194
Omar Abdelhafith Avatar answered Sep 28 '22 10:09

Omar Abdelhafith