How do I get hour and minutes from NSDate?

后端 未结 8 1316
清歌不尽
清歌不尽 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 06:13

    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];
    
    0 讨论(0)
  • 2020-12-02 06:17

    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
    
    0 讨论(0)
提交回复
热议问题