Reputation: 31
What is the best way to convert seconds into (Year:Month:Day Hour:Minutes:Seconds) time?
Let's say I have 959040000 seconds (1 year 5 months), are there any specialized classes/techniques in .NET that would allow me to convert those 959040000 seconds into (Year:Month:Day Hour:Minutes:Seconds) like to DateTime or something?
Upvotes: 3
Views: 7584
Reputation: 26645
To tell the truth, you can't because it depends on the start date i.e. 30 days may be 1 month 1 day, or 1 month 2 days, or less than a month or 365 days will be less than a year if it's a leap year.
But, you can use:
TimeSpan diff = TimeSpan.FromSeconds(959040000);
string formatted = string.Format(
CultureInfo.CurrentCulture,
"{0} years, {1} months, {2} days, {3} hours, {4} minutes, {5} seconds",
diff.Days / 365,
(diff.Days - (diff.Days / 365) * 365)/30,
(diff.Days - (diff.Days / 365) * 365) - ((diff.Days - (diff.Days / 365) * 365) / 30)*30,
diff.Hours,
diff.Minutes,
diff.Seconds);
Console.WriteLine(formatted);
Output is:
30, 5, 0, 0, 0, 0
If you enter 856044326
the output will be:
27, 1, 22, 22, 5, 26
Upvotes: 3
Reputation: 12837
use the TimeSpan class:
var ts = new TimeSpan(0, 0, 959040000);
int days = ts.Days;
int years = days / 365;
....
Upvotes: 5
Reputation: 11114
Here is another trick.. you can also use time span
DateTime date, date2;
date = date2 = DateTime.Now;
date2= date2.AddSeconds(959040000);
var totaldays = (date2 - date).TotalDays;
var totalHours = (date2 - date).TotalHours;
var Totalmin = (date2 - date).TotalMinutes;
var years = totaldays / 365;
Upvotes: -1