How to convert seconds into weeks, days, hours, minutes, and seconds in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

/*
Use integer division and modulo:

1 minute = 60 seconds
1 hour   = 60 minutes
1 day    = 24 hours
1 week   = 7 days
*/

/*
    Convert a total number of seconds into weeks, days, hours,
    minutes, and seconds. The function receives the total seconds
    and returns each component in a struct.
*/
type TimeParts struct {
    Weeks   int64
    Days    int64
    Hours   int64
    Minutes int64
    Seconds int64
}

func convertSeconds(totalSeconds int64) TimeParts {
    const SECS_PER_MIN int64 = 60
    const SECS_PER_HOUR int64 = 60 * SECS_PER_MIN
    const SECS_PER_DAY int64 = 24 * SECS_PER_HOUR
    const SECS_PER_WEEK int64 = 7 * SECS_PER_DAY

    // Compute each unit using integer division and modulo
    weeks := totalSeconds / SECS_PER_WEEK
    totalSeconds %= SECS_PER_WEEK

    days := totalSeconds / SECS_PER_DAY
    totalSeconds %= SECS_PER_DAY

    hours := totalSeconds / SECS_PER_HOUR
    totalSeconds %= SECS_PER_HOUR

    minutes := totalSeconds / SECS_PER_MIN
    seconds := totalSeconds % SECS_PER_MIN

    return TimeParts{
        Weeks:   weeks,
        Days:    days,
        Hours:   hours,
        Minutes: minutes,
        Seconds: seconds,
    }
}

func main() {
    var seconds int64 = 1_000_000

    result := convertSeconds(seconds)

    fmt.Printf("%d weeks, %d days, %d hours, %d minutes, %d seconds\n",
        result.Weeks, result.Days, result.Hours, result.Minutes, result.Seconds)
}



/*
run:

1 weeks, 4 days, 13 hours, 46 minutes, 40 seconds

*/

 



answered May 20 by avibootz

Related questions

...