How do I create the current date (or any date) as an NSDate without hours, minutes and seconds?
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;
}
How do I create the current date (or any date) as an NSDate without hours, minutes and seconds?
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;
}
How to change the current day's hours and minutes in Swift?
Be aware that for locales that uses Daylight Saving Times, on clock change days, some hours may not exist or they may occur twice. Both solutions below return a Date?
and use force-unwrapping. You should handle possible nil
in your app.
Swift 3, 4, 5 and iOS 8 / OS X 10.9 or later
let date = Calendar.current.date(bySettingHour: 9, minute: 30, second: 0, of: Date())!
Swift 2
Use NSDateComponents
/ DateComponents
:
let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let now = NSDate()
let components = gregorian.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: now)
// Change the time to 9:30:00 in your locale
components.hour = 9
components.minute = 30
components.second = 0
let date = gregorian.dateFromComponents(components)!
Note that if you call print(date)
, the printed time is in UTC. It's the same moment in time, just expressed in a different timezone from yours. Use a NSDateFormatter
to convert it to your local time.
How to get the current time as datetime
Update for Swift 3:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
I do this:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
See the same question in objective-c How do I get hour and minutes from NSDate?
Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
How to create NSDate like '2013-05-11 00:00:00'
If you want to set the components of a date, you want to look at NSCalendar's methods for dealing with date components:
NSDate *today = [NSDate date];
// Get the year, month, day from the date
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:today];
// Set the hour, minute, second to be zero
components.hour = 0;
components.minute = 0;
components.second = 0;
// Create the date
NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:components];
Swift NSDate create var with hour and minute only
The quick way, getting the nsdate from your string elements and then convert the nsdate back to a string if you want to :
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
let hour = 08
let minutes = 32
let time = formatter.dateFromString("\(hour):\(minutes)")!
let finalTime = formatter.stringFromDate(time)
print(time)
print(finalTime)
How to calculate remaining Days, Hours, Mins and seconds from given date?
You are making mistake here, your fromDate
should be the today date ie [NSDate date]
and with toDate
will be your startDate
. So your code should be something like this.
NSString *end = [[self.eventsArray valueForKey:@"date_time"]objectAtIndex:0];
NSDateFormatter *date = [[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//Start date
NSDate *startDate = [NSDate date];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond
fromDate:startDate
toDate:endDate
options:0];
NSLog(@"day : %ld H: %ld M : %ld S:%ld", [components day], (long)[components hour],(long)[components minute],(long)[components second]);
Related Topics
Error Setting Text in Collection View Cell
Seed and Maintain Cloudkit Public Database Without Requiring Icloud Login
"Invalid Predicate: Nil Rhs" for Second Argument in Nspredicate Format
iOS Apns "Best-Effort" Fallback
Cgcolorgetcomponents() Not Returning the Correct Values for Black and for White
How to Run Multiple iOS Simulators at Once
Nsdateformatter Returns Nil in Swift and iOS Sdk 8.0
How to Find Serial Number, Imei Number Using iOS Sdk
How to Add Text, Shape and Signature in Photo Markup with Pencil Kit
Codesign Returned Errsecinternalcomponent in High Sierra
Skspritenode Position Changes to 0,0 for No Reason
Customizing Uilocalnotification's Alert