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,872 questions

51,796 answers

573 users

How to turn a total number of seconds into years, months, days, minutes and seconds in C#

1 Answer

0 votes
using System;

public struct TimeBreakdown
{
    public int Years { get; }
    public int Months { get; }
    public int Days { get; }
    public int Hours { get; }
    public int Minutes { get; }
    public int Seconds { get; }

    public TimeBreakdown(int years, int months, int days, int hours, int minutes, int seconds) {
        Years = years;
        Months = months;
        Days = days;
        Hours = hours;
        Minutes = minutes;
        Seconds = seconds;
    }
}

public class Program
{
    public static void Main()
    {
        long inputSeconds = 102_420_852;
        TimeBreakdown result = GetTimeBreakdown(inputSeconds);

        Console.WriteLine($"Years:   {result.Years}");
        Console.WriteLine($"Months:  {result.Months}");
        Console.WriteLine($"Days:    {result.Days}");
        Console.WriteLine($"Hours:   {result.Hours}");
        Console.WriteLine($"Minutes: {result.Minutes}");
        Console.WriteLine($"Seconds: {result.Seconds}");
    }

    public static TimeBreakdown GetTimeBreakdown(long totalSeconds)
    {
        // Safe reference date to avoid overflow
        DateTime start = new DateTime(2000, 1, 1);
        DateTime end = start.AddSeconds(totalSeconds);

        // Calculate years
        int years = end.Year - start.Year;
        DateTime temp = start.AddYears(years);

        if (temp > end) {
            years--;
            temp = start.AddYears(years);
        }

        // Calculate months
        int months = 0;
        while (temp.AddMonths(1) <= end) {
            temp = temp.AddMonths(1);
            months++;
        }

        // Remaining time
        TimeSpan remaining = end - temp;

        return new TimeBreakdown(
            years,
            months,
            remaining.Days,
            remaining.Hours,
            remaining.Minutes,
            remaining.Seconds
        );
    }
}



/*
run:

Years:   3
Months:  2
Days:    30
Hours:   10
Minutes: 14
Seconds: 12

*/

 



answered Jan 21 by avibootz

Related questions

...