Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create the current date (or any date) as an NSDate without hours, minutes and seconds?

I need to create an NSDate of the current date (or on any NSDate) without the hours, minutes and seconds and keep it as an NSDate, in as few lines of as possible?

I need to perform some calculations on dates and having hours, minutes and seconds cause problems, I need absolute dates (I hope absolute is the right phrase). Its for an iPhone app.

I'm creating dates with [NSDate date] which add hours, minutes and seconds. Also I'm adding months to dates which I think caters for day light savings as I get 2300 hours on some dates.

So ideally I need a function to create absolute NSDates from NSDates.

I know I asked a similar question earlier, but I need to end up with NSDate not a string and I'm a little concerned about specifying a date format e.g. yyyy etc.

like image 699
Jules Avatar asked Jan 28 '11 20:01

Jules


People also ask

What is NSDate?

The NSDate class provides methods for comparing dates, calculating the time interval between two dates, and creating a new date from a time interval relative to another date.

How do I increment a date in Swift?

Adding Datelet monthsToAdd = 2 let daysToAdd = 1 let yearsToAdd = 1 let currentDate = Date() var dateComponent = DateComponents() dateComponent. month = monthsToAdd dateComponent.

How do you subtract two dates in Swift?

let calendar = NSCalendar. current as NSCalendar // Replace the hour (time) of both dates with 00:00 let date1 = calendar. startOfDay(for: startDateTime) let date2 = calendar. startOfDay(for: endDateTime) let flags = NSCalendar.


1 Answers

First, you have to understand that even if you strip hours, minutes and seconds from an NSDate, it will still represent a single moment in time. You will never get an NSDate to represent an entire day like 2011-01-28; it will always be 2011-01-28 00:00:00 +00:00. That implies that you have to take time zones into account, as well.

Here is a method (to be implemented as an NSDate category) that returns an NSDate at midnight UTC on the same day as self:

- (NSDate *)midnightUTC {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                                   fromDate:self];
    [dateComponents setHour:0];
    [dateComponents setMinute:0];
    [dateComponents setSecond:0];

    NSDate *midnightUTC = [calendar dateFromComponents:dateComponents];
    [calendar release];

    return midnightUTC;
}
like image 94
Ole Begemann Avatar answered Nov 15 '22 08:11

Ole Begemann