How do I get hour and minutes from NSDate?
Solution 1:
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
Solution 2:
If you only need it for presenting as a string the following code is much easier
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSString *startTimeString = [formatter stringFromDate:startTimePicker.date];
Solution 3:
This seems to me to be what the question is after, no need for formatters:
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
Solution 4:
NSDateComponents
All you need can be found here:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendars.html
Solution 5:
If you were to use the C library then this could be done:
time_t t;
struct tm * timeinfo;
time (&t);
timeinfo = localtime (&t);
NSLog(@"Hour: %d Minutes: %d", timeinfo->tm_hour, timeinfo->tm_min);
And using Swift:
var t = time_t()
time(&t)
let x = localtime(&t)
println("Hour: \(x.memory.tm_hour) Minutes: \(x.memory.tm_min)")
For further guidance see: http://www.cplusplus.com/reference/ctime/localtime/