Days, hours, minutes, seconds between two dates

后端 未结 9 1019
挽巷
挽巷 2020-12-01 07:29

I have two dates, one less than the other. I want to create a string such as this one

\"0 days, 0 hours, 23 minutes, 18 seconds\"

representing the differenc

相关标签:
9条回答
  • 2020-12-01 07:55

    Use a TimeSpan

    DateTime startTime = DateTime.Now;
    
    DateTime endTime = DateTime.Now.AddSeconds( 75 );
    
    TimeSpan span = endTime.Subtract ( startTime );
    Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
    Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
    Console.WriteLine( "Time Difference (hours): " + span.Hours );
    Console.WriteLine( "Time Difference (days): " + span.Days );
    
    String yourString = string.Format("{0} days, {1} hours, {2} minues, {3} seconds",
        span.Days, span.Hours, span.Minutes, span.Seconds);
    
    0 讨论(0)
  • 2020-12-01 07:58

    Use the TimeSpan class, which you'll get when you subtract the dates.

    You can format the output using standard or custom format strings.

    "0 days, 0 hours, 23 minutes, 18 seconds"

    can be had with something like:

    TimeSpan ts = DateTime.Now - DateTime.Today;
    Console.WriteLine(
       string.Format("{0:%d} days, {0:%h} hours, {0:%m} minutes, {0:%s} seconds", ts)
    );
    

    IMO, it's cleaner and easier to use string.Format instead of having to escape the words in your format string (which you'd need if you just used .ToString) or building it up manually.

    0 讨论(0)
  • 2020-12-01 08:02

    TimeSpan is the object you need:

    TimeSpan span = (DateTime.Now - DateTime.Now);
    
    String.Format("{0} days, {1} hours, {2} minutes, {3} seconds", 
        span.Days, span.Hours, span.Minutes, span.Seconds);
    
    0 讨论(0)
提交回复
热议问题