Monday, December 13, 2010

Time in HH:MM:SS format from the second

Shout it kick it on DotNetKicks.com
Problem
In my project I stored date difference in seconds but the real issue we have to display this difference of second in  form of HOURS, MINUTE and SECONDS.

Solution
So to achieve above task we use TimeSpan.FromSeconds available in the C# which takes seconds as input and gives TimeSpan as output. From which I get HOURS, MINUTES and SECOND by inputing seconds only. Below is code sample to do that

public string getFormattedTimeFromSecond(double second)
    {

        TimeSpan t = TimeSpan.FromSeconds(second);

        string formatedTime = string.Format("{0:D2}H:{1:D2}M:{2:D2}S",
                                t.Hours,
                                t.Minutes,
                                t.Seconds);

        return formatedTime;
}

No comments:

Post a Comment