How do I get hour and minutes from NSDate?
Use an NSDateFormatter to convert string1
into an NSDate
, then get the required NSDateComponents:
Obj-C:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"<your date format goes here"];
NSDate *date = [dateFormatter dateFromString:string1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
Swift 1 and 2:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "Your date Format"
let date = dateFormatter.dateFromString(string1)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Hour, .Minute], fromDate: date)
let hour = comp.hour
let minute = comp.minute
Swift 3:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "Your date Format"
let date = dateFormatter.date(from: string1)
let calendar = Calendar.current
let comp = calendar.dateComponents([.hour, .minute], from: date)
let hour = comp.hour
let minute = comp.minute
More about the dateformat is on the official unicode site
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 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.
In Objective-C, to get the current hour and minute as integers, we need to use NSDateComponents and NSCalendar?
NSDate
just holds the time that has passed since a certain reference date, to get more meaningful numbers out of this (eg. after taking care of DST, leap years and all the other stupid time stuff), you have to use NSDateComponents
with the appropriate NSCalendar
.
How to set hour/minute/second in NSDateComponents with a string?
This is the correct answer. You must separate the string individually, and input them into the components.
NSArray *results = [storeOpen componentsSeparatedByString:@":"];
if ([results count] == 3) {
NSLog(@"1 - %d", [[results objectAtIndex:0] intValue]);
NSLog(@"2 - %d", [[results objectAtIndex:1] intValue]);
NSLog(@"3 - %d", [[results objectAtIndex:2] intValue]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [calendar components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
[comps setHour:[[results objectAtIndex:0] intValue]];
[comps setMinute:[[results objectAtIndex:1] intValue]];
[comps setSecond:[[results objectAtIndex:2] intValue]];
NSDate *dateFromComps = [calendar dateFromComponents:comps];
NSDate zero out hour minuts and seconds
Always helpful:
WWDC Videos
2011 Session 117 - Performing Calendar Calculations
2013 Session 227 - Solutions to Common Date and Time Challenges
This contains the information you probably want:
Session 227 @ 13m25s, "Common Operations" / "Calculate Midnight".
How to set hour minute in nsdate programmatically?
If you need to calculate specific real instances in time e.g. 3:20:30 PM Oct 23, 2010, then you want to use NSCalendar which lets you decompose dates and do date related calculations.
Word of warning. Date and time calculations are surprisingly complex and detailed. Expect to spend a couple of hours learning the API.
Related Topics
Change Width of a Uibarbuttonitem in a Uinavigationbar
Sharing an Image Between Two Viewcontrollers During a Transition Animation
iOS - Push Viewcontroller from Code and Storyboard
iOS 8 Uiactivityviewcontroller and Uialertcontroller Button Text Color Uses Window's Tintcolor
Bounding Box from Vndetectrectanglerequest Is Not Correct Size When Used as Child Vc
iPhone Uitableview. How Do Turn on the Single Letter Alphabetical List Like the Music App
Could Not Find Module for Target 'X86_64-Apple-Ios-Simulator'
How to Make Return Key on iPhone Make Keyboard Disappear
Autolayout, Unable to Simultaneously Satisfy Constraints
Animating/Moving Views Under Usage of Autolayout
Setting "Applelanguages" Doesn't Change App Language
Firebase Limit on the Number of Observers/Listeners
Custom Class Clusters in Swift
Playing Back Audio Using Avaudioplayer iOS 7
How to Remove Border of the Navigationbar in Swift
Xcode Exception Breakpoint Doesn't Print Details of the Exception Being Thrown