How do I get hour and minutes from NSDate?

后端 未结 8 1370
清歌不尽
清歌不尽 2020-12-02 05:26

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

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


        
8条回答
  •  自闭症患者
    2020-12-02 05:52

    Use an NSDateFormatter to convert string1 into an NSDate, then get the required NSDateComponents:

    Obj-C:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"

    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

提交回复
热议问题