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.
With iOS 8, Apple introduced a helper method to retrieve the
hour
,minute
,second
andnanosecond
from an NSDate object.Objective-C
Swift
Use an NSDateFormatter to convert
string1
into anNSDate
, then get the required NSDateComponents:Obj-C:
Swift 1 and 2:
Swift 3:
More about the dateformat is on the official unicode site
Swift 2.0
Please do take note of the cast to String in the print statement, you can easily assign that value to variables, like this:
Then you can concatenate values like this:
Swift 2.0
You can do following thing to get hours and minute from a date :
This seems to me to be what the question is after, no need for formatters:
If you were to use the C library then this could be done:
And using Swift:
For further guidance see: http://www.cplusplus.com/reference/ctime/localtime/