我如何从NSDate获得小时和分钟?
在我的应用程序中,我需要分别得到小时和分钟:
In my application I need to get the hour and minute separately:
NSString *currentHour=[string1 substringWithRange: NSMakeRange(0,2)];
int currentHourInNumber=[currentHour intValue];
考虑 string1
包含 11:59:13 AM
来自datepicker。
Consider string1
contains 11:59:13 AM
which is coming from datepicker.
这里如果我使用上面的代码,如果它更大,可以获得一小时比其他我需要更改 NSMakeRange(0,1)
以获得1到9之间的小时。
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.
使用 NSDateFormatter 将 string1
转换为 NSDate
,然后获取所需的 NSDateComponents :
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和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
关于 dateformat 在官方unicode上e
More about the dateformat is on the official unicode site