我如何从NSDate获得小时和分钟?


113

在我的应用程序中,我需要分别获取小时和分钟:

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

考虑string1包含11:59:13 AM来自日期选择器的内容。

在这里,如果我使用上面的代码,则大于9 NSMakeRange(0,1)可以获取小时。否则,我需要更改以获取1到9之间的小时。

是否有获取小时,分钟等的方法?

在此先感谢您提供示例代码。


Answers:


262

使用NSDateFormatter转换string1NSDate,然后获取所需的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];

迅捷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

迅捷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网站上


嗨,还有一个疑问,是否可以更改NSDate中的小时,分​​钟
mac

要更改小时和分钟,请查看NSDate的+ dateWithTimeIntervalSinceReferenceDate:。该方法使您可以添加迄今特定的秒数(并返回新的日期)。
ThomasMüller,2010年

在iOS上,“组件”仅从8.0版开始可用。<8.0怎么样?
Rhuantavan

2
@Rhuantavan developer.apple.com/library/ios/documentation/Cocoa/Reference/...: “可用在IOS 2.0和更高”。我肯定已经使用此API多年了。
ThomasMüller'2

我猜这是XCode中的错误,因为它报告的是8.0。我应该检查过来源或在线文档。我的错。
Rhuantavan

52

如果只需要它以字符串形式显示,则下面的代码会容易得多

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];

NSString *startTimeString = [formatter stringFromDate:startTimePicker.date];

45

在我看来,这就是所要解决的问题,不需要格式化程序:

NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

1
如何获得上午或下午?
亚拉曼达鲁


4

如果要使用C库,则可以这样做:

time_t t;
struct tm * timeinfo;

time (&t);
timeinfo = localtime (&t);

NSLog(@"Hour: %d Minutes: %d", timeinfo->tm_hour, timeinfo->tm_min);

并使用Swift:

var t = time_t()
time(&t)
let x = localtime(&t)

println("Hour: \(x.memory.tm_hour) Minutes: \(x.memory.tm_min)")

有关更多指导,请参见:http : //www.cplusplus.com/reference/ctime/localtime/


4

与iOS 8,苹果推出了一个辅助方法来检索hourminutesecondnanosecond从一个NSDate对象。

目标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);

迅速

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)")
}

3

雨燕2.0

您可以执行以下操作从日期获取小时和分钟:

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

使用NSDateFormatter可获得简短详细信息。
yo2bh

2

雨燕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))

请注意打印语句中对String的强制转换,您可以轻松地将该值分配给变量,如下所示:

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

然后,您可以将值串联起来:

var compoundString = "\(hour):\(minute)"
print(compoundString)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.