Search code examples
swifttimedaysseconds

How to display seconds in year, day format in swift


All i need to do is to change the way that xcode displaying my values in. My code currently displaying the age of something in minutes e.g 4503mint . I want to be able to display these values in the following format 3 days 3 hours 3 mint rather than 4503 mint. Really appreciate your help. Regards


Solution

  • You said:

    My code currently displaying the age of something in minutes e.g 4503mint . I want to be able to display these values in the following format 3 days 3 hours 3 mint rather than 4503 mint.

    You can format this using NSDateComponentsFormatter. Just multiply the number of minutes by 60 to get the NSTimeInterval, and then you can supply that to the formatter:

    let formatter = NSDateComponentsFormatter()
    formatter.unitsStyle = .Full
    
    let minutes = 4503
    let timeInterval = NSTimeInterval(minutes * 60)
    print(formatter.stringFromTimeInterval(timeInterval))
    

    That will produce "3 days, 3 hours, 3 minutes" (or in whatever format appropriate for the locale for that device).

    See NSDateComponentsFormatter Reference for more information.