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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to convert days into human-readable years, months and days in Go

2 Answers

0 votes
package main

import (
    "fmt"
    "time"
)

type YMD struct {
    Years  int
    Months int
    Days   int
}

func SplitDays(totalDays int) YMD {
    start := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
    end := start.AddDate(0, 0, totalDays)

    years := end.Year() - start.Year()
    months := int(end.Month()) - int(start.Month())
    days := end.Day() - start.Day()

    // Normalize negative days
    if days < 0 {
        months--
        prevMonth := end.AddDate(0, -1, 0)
        days += daysInMonth(prevMonth.Year(), prevMonth.Month())
    }

    // Normalize negative months
    if months < 0 {
        months += 12
        years--
    }

    return YMD{years, months, days}
}

func daysInMonth(year int, month time.Month) int {
    // Day 0 of next month = last day of this month
    t := time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC)
    
    return t.Day()
}

func main() {
    r := SplitDays(452)
    
    fmt.Printf("%d years, %d months, %d days\n", r.Years, r.Months, r.Days)
}


/*
run:

1 years, 2 months, 28 days

*/

 



answered Jan 1 by avibootz
0 votes
package main

import (
    "fmt"
)

type YMD struct {
    Years  int
    Months int
    Days   int
}

func SplitDays(totalDays int) YMD {
    years := totalDays / 365
    totalDays %= 365

    months := totalDays / 30
    totalDays %= 30

    days := totalDays

    return YMD{years, months, days}
}


func main() {
    r := SplitDays(452)
    
    fmt.Printf("%d years, %d months, %d days\n", r.Years, r.Months, r.Days)
}


/*
run:

1 years, 2 months, 27 days

*/

 



answered Jan 1 by avibootz

Related questions

...