114

In my application I need to get the hour and minute separately:

NSString *currentHour=[string1 substringWithRange: NSMakeRange(0,2)];
        int currentHourInNumber=[currentHour intValue];

Consider string1 contains 11:59:13 AM which is coming from datepicker.

Here if I use above code, it's okay to get hour if it's greater than 9. Else I need to change NSMakeRange(0,1) to get hour between 1 to 9.

Are there any methods to get the hour, minutes, etc?

Thanks in advance, please provide me sample code.

Leo Dabus
  • 198,248
  • 51
  • 423
  • 494
mac
  • 4,650
  • 7
  • 29
  • 33
  • Possible duplicate of [How to get the hour of the day with Swift?](https://stackoverflow.com/questions/24137692/how-to-get-the-hour-of-the-day-with-swift) – J-Dizzle Jan 20 '18 at 19:30

8 Answers8

264

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

Felipe Plets
  • 5,192
  • 3
  • 28
  • 47
Thomas Müller
  • 15,109
  • 6
  • 40
  • 47
  • Hi One more doubt, is it possible to change the hour, minute in NSDate – mac May 28 '10 at 07:21
  • To change the hour and minute, maybe look into NSDate's + dateWithTimeIntervalSinceReferenceDate:. That method lets you add a specific amount of seconds to date (and return a new date). – Thomas Müller May 30 '10 at 01:41
  • On iOS, "components" is only available since version 8.0. How about < 8.0? – Rhuantavan Feb 03 '15 at 10:19
  • 2
    @Rhuantavan https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/occ/instm/NSCalendar/components:fromDate: "Available in iOS 2.0 and later." I have definitely use this API for years. – Thomas Müller Feb 03 '15 at 23:32
  • I guess it is a bug in XCode since it was reporting this to be 8.0. I should have checked the sources or online docs. My bad. – Rhuantavan Feb 04 '15 at 08:23
53

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];
pkamb
  • 26,648
  • 20
  • 124
  • 157
Gil Margolin
  • 1,663
  • 19
  • 21
45

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];
Stan James
  • 2,277
  • 26
  • 35
HenryRootTwo
  • 2,419
  • 1
  • 22
  • 26
6

NSDateComponents

All you need can be found here:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendars.html

Pang
  • 8,605
  • 144
  • 77
  • 113
Paul Lynch
  • 19,629
  • 4
  • 35
  • 41
4

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/

sketchyTech
  • 5,137
  • 28
  • 52
4

With iOS 8, Apple introduced a helper method to retrieve the hour, minute, second and nanosecond from an NSDate object.

Objective-C

NSDate *date = [NSDate currentDate];
NSInteger hour = 0;
NSInteger minute = 0;
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
[currentCalendar getHour:&hour minute:&minute second:NULL nanosecond:NULL fromDate:date];
NSLog(@"the hour is %ld and minute is %ld", (long)hour, (long)minute);

Swift

let date = NSDate()
var hour = 0
var minute = 0
let calendar = NSCalendar.currentCalendar()
if #available(iOS 8.0, *) {
    calendar.getHour(&hour, minute: &minute, second: nil, nanosecond: nil, fromDate: date)
    print("the hour is \(hour) and minute is \(minute)")
}
newDeveloper
  • 1,325
  • 1
  • 16
  • 26
3

Swift 2.0

You can do following thing to get hours and minute from a date :

let dateFromat = NSDateFormatter()
dateFromat.dateFormat = "hh:mm a"
let date = dateFromat.dateFromString(string1) // In your case its string1
print(date) // you will get - 11:59 AM
yo2bh
  • 988
  • 12
  • 21
  • Use [NSDateFormatter](http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/) for brief details. – yo2bh May 24 '16 at 10:32
2

Swift 2.0

    let dateNow = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
    let minute = calendar.component(NSCalendarUnit.Minute, fromDate: dateNow)
    print(String(hour))
    print(String(minute))

Please do take note of the cast to String in the print statement, you can easily assign that value to variables, like this:

var hoursString = String(hour)
var minutesString = String(minute)

Then you can concatenate values like this:

var compoundString = "\(hour):\(minute)"
print(compoundString)
Juan Boero
  • 5,451
  • 37
  • 56