Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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

...