What is the most efficient way to obtain an NSDate object that represents midnight of the current day?
New API in iOS 8
iOS 8 includes a new method on NSCalendar called startOfDayForDate, which is really easy to use:
let startOfToday = NSCalendar.currentCalendar().startOfDayForDate(NSDate())
Apple's description:
This API returns the first moment date of a given date.
Pass in [NSDate date], for example, if you want the start of "today".
If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist.
Update, regarding time zones:
Since startOfDayForDate is a method on NSCalendar, it uses the NSCalendar's time zone. So if I wanted to see what time it was in New York, when today began in Los Angeles, I could do this:
let losAngelesCalendar = NSCalendar.currentCalendar().copy() as! NSCalendar
losAngelesCalendar.timeZone = NSTimeZone(name: "America/Los_Angeles")!
let dateTodayBeganInLosAngeles = losAngelesCalendar.startOfDayForDate(NSDate())
dateTodayBeganInLosAngeles.timeIntervalSince1970
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .ShortStyle
dateFormatter.timeZone = NSTimeZone(name: "America/New_York")!
let timeInNewYorkWhenTodayBeganInLosAngeles = dateFormatter.stringFromDate(dateTodayBeganInLosAngeles)
print(timeInNewYorkWhenTodayBeganInLosAngeles) // prints "Jul 29, 2015, 3:00 AM"
Try this:
NSDate *const date = NSDate.date;
NSCalendar *const calendar = NSCalendar.currentCalendar;
NSCalendarUnit const preservedComponents = (NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay);
NSDateComponents *const components = [calendar components:preservedComponents fromDate:date];
NSDate *const normalizedDate = [calendar dateFromComponents:components];
NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[cal setTimeZone:[NSTimeZone systemTimeZone]];
NSDateComponents * comp = [cal components:( NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]];
[comp setMinute:0];
[comp setHour:0];
[comp setSecond:0];
NSDate *startOfToday = [cal dateFromComponents:comp];
If you mean midnight as 23:59 then set component's hour as 23 and minutes as 59.
Swift:
let cal = NSCalendar.currentCalendar()
//tip:NSCalendarUnit can be omitted, but with the presence of it, you can take advantage of Xcode's auto-completion
var comps = cal.components(NSCalendarUnit.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit | .HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit, fromDate: NSDate())
comps.hour = 0
comps.minute = 0
comps.second = 0
let midnightOfToday = cal.dateFromComponents(comps)!
Swift 2.2:
let cal = NSCalendar.currentCalendar()
let comps = cal.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: NSDate())
comps.hour = 0
comps.minute = 0
comps.second = 0
let midnightOfToday = cal.dateFromComponents(comps)!
Objective-C:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps = [cal components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSDate *midnightOfToday = [cal dateFromComponents:comps];
You could use the following method to get the midnight value for an NSDate.
- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate
{
// Use the user's current calendar and time zone
NSCalendar *calendar = [NSCalendar currentCalendar];
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
[calendar setTimeZone:timeZone];
// Selectively convert the date components (year, month, day) of the input date
NSDateComponents *dateComps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:inputDate];
// Set the time components manually
[dateComps setHour:0];
[dateComps setMinute:0];
[dateComps setSecond:0];
// Convert back
NSDate *beginningOfDay = [calendar dateFromComponents:dateComps];
return beginningOfDay;
}
Thkis is taken from here website.
From iOS8, you can use startDayForDate.
So, in order to get the start of today (Objective -C):
NSDate * midnight;
midnight = [[NSCalendar currentCalendar] startOfDayForDate: [NSDate date]];
try this:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *now = [NSDate date];
NSDateComponents *components = [gregorian components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:now];
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"MM/dd/yyyy HH:mm:ss.SSS"];
NSLog(#"%#",[df stringFromDate:[gregorian dateFromComponents:components]]);
NSDate *now = [NSDate date];
NSDate *beginningOfToday = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfToday interval:NULL forDate:now];
You could use NSCalendar's dateBySettingHour:minute:second:ofDate:options:
So it would be as easy as doing:
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSDate *midnight = [calendar dateBySettingHour:0 minute:0 second:0 ofDate:[NSDate date] options:0];
let calendar = NSCalendar.currentCalendar()
let unitFlags: NSCalendarUnit = [.Year, .Month, .Day, .Minute, .Second]
let components = calendar.components(unitFlags , fromDate: NSDate())
components.hour = 0
components.minute = 0
components.second = 0
//Gives Midnight time of today
let midnightOfToday = calendar.dateFromComponents(components)!
Related
Im trying to figure out this timestamp format, but it looks weird to me.
There is a timestamp in that format: 184930.60
Explanation is: "This is UTC time since midnight in the form HH:MM:SS.SS."
It looks like number of seconds (based on change in file, for 20Hz GPS module), but it is 51h when you convert these seconds, and this can't be 51h after midnight.
Any idea how to convert that into nsdate?
Details about file format: https://racelogic.support/01VBOX_Automotive/01General_Information/Knowledge_Base/VBO_file_format
This is working example:
-(NSDate *)getDateFromDecimalTime:(double)decimalTime{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HHmmss.SS"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSDate *date = [formatter dateFromString:[NSString stringWithFormat:#"%f", decimalTime]];
//gather current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];
//gather date components from date
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
// Get current year/day/month
NSDate *now = [NSDate date];
// Specify which units we would like to use
unsigned units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar *calendar2 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar2 components:units fromDate:now];
//set date components
[dateComponents setDay:[components day]];
[dateComponents setMonth:[components month]];
[dateComponents setYear:[components year]];
//save date relative from date
NSDate *completeDate = [calendar dateFromComponents:dateComponents];
return completeDate;
}
Is it possible to parse out date components from an NSString-based date? For instance, if I have an NSDateFormatter with yyyy-MM-dd HH:mm:ss.SSS ZZZ, how can I get an NSDateComponents object from this string directly?
Specifically, I'd like to preserve timezones, and differentiate this NSDateComponents object with one created from the yyyy-MM-dd format.
Not so directly, but with a few steps:
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss.SSS ZZZ"];
NSString *dateString = #"2016-03-15 12:00:00.000 +0800";
NSDate *date = [formatter dateFromString:dateString];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitTimeZone fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSTimeZone *timeZone = [components timeZone];
I have an NSDate object *myDate.I can get the week day from this date and I want to set the weekday to an integer c and get the new date object in that week only.
I searched for it and I found the answer,here is the code..
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:comps toDate:[NSDate date] options:0];
NSLog(#"new date==%#",newDate);
This will return date of the next day.
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MMM dd, yyy"];
date = [formatter dateFromString:string];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger day = [components day];
NSInteger weekday = [components weekday]; // if necessary
Given an NSDate and an NSCalendar, how do I determine the number of hours in the day that follows the given date. This would be 23, 24, or 25, depending on whether the following day is entering daylight savings (23), normal (24) or exiting daylight savings (25).
You can ask the calendar how long any unit is (and when that unit starts) with rangeOfUnit:startDate:interval:forDate:.
// Test date (the day DST begins)
NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = 2012;
components.month = 3;
components.day = 11;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [calendar dateFromComponents:components];
NSTimeInterval dayLength;
[calendar rangeOfUnit:NSDayCalendarUnit startDate:NULL interval:&dayLength forDate:date];
NSLog(#"%f seconds", dayLength);
Note that rangeOfUnit:... can techincally fail and return NO, but if you control the inputs that shouldn't be able to happen.
// Test input
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy MM dd HH:mm:ss";
NSDate *referenceDate = [formatter dateFromString:#"2012 03 24 13:14:14"];
// Get reference date with day precision
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:unitFlags fromDate:referenceDate];
NSDate *today = [calendar dateFromComponents:components];
// Set components to add 1 day
components = [[NSDateComponents alloc] init];
components.day = 1;
// The day after the reference date
NSDate *tomorrow = [calendar dateByAddingComponents:components toDate:today options:0];
// The day after that
NSDate *afterTomorrow = [calendar dateByAddingComponents:components toDate:tomorrow options:0];
// Difference in hours: 23, 24 or 25
NSUInteger hours = [afterTomorrow timeIntervalSinceDate:tomorrow] / 3600;
I'm trying to figure out what day (i.e. Monday, Friday...) of any given date (i.e. Jun 27th, 2009)
Thank you.
I've been doing:
NSDateFormatter* theDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[theDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[theDateFormatter setDateFormat:#"EEEE"];
NSString *weekDay = [theDateFormatter stringFromDate:[NSDate date]];
This has the added bonus of letting you choose how you'd like the weekday to be returned (by changing the date format string in the setDateFormat: call
Lots more information at:
http://developer.apple.com/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369
You may have a look to the NSDate and NSCalendar classes.
For example, here and here
They provide the following code:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =
[gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];
Use NSCalendar and NSDateComponents. As shown in the NSDateComponents documentation:
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
Here's what I wound up with, which works exactly as intended. It takes a date, alters the date to be the first of the month, and gets the day of that date:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
NSDateComponents *monthDateComponents = [[NSCalendar currentCalendar] components: NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear |
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate: date];
// build date as start of month
monthDateComponents.year = components.year;
monthDateComponents.month = components.month;
monthDateComponents.day = 1;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
// [gregorian setFirstWeekday:1];
NSDate *builtDate =[gregorian dateFromComponents: monthDateComponents];
// NSDateComponents *weekdayComponents =[gregorian components: NSCalendarUnitWeekday fromDate: builtDate];
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:#"E"];
NSString *firstDay = [df stringFromDate:builtDate];
if([firstDay isEqual:#"Sun"]) // do for the other 6 days as appropriate
return 7;