Days, hours, minutes, seconds between two dates

后端 未结 9 1018
挽巷
挽巷 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:40

    When you subtract one DateTime from another, you get a TimeSpan instance, which exposes those values.

    TimeSpan diff = DateTime.Now - DateTime.Today;
    string formatted = string.Format(
                           CultureInfo.CurrentCulture, 
                           "{0} days, {1} hours, {2} minutes, {3} seconds", 
                           diff.Days, 
                           diff.Hours, 
                           diff.Minutes, 
                           diff.Seconds);
    
    0 讨论(0)
  • 2020-12-01 07:42

    Have you tried using

    TimeSpan()
    

    that can certainly do what you want

    0 讨论(0)
  • 2020-12-01 07:43
    TimeSpan diffTime = dateTimeNew -PreviousDate;
    int days=diffTime.Days;
    int hours=diffTime.Hours;
    int minutes=diffTime.Minutes;
    int seconds=diffTime.Seconds;
    
    0 讨论(0)
  • 2020-12-01 07:51

    Don't forget that if you want this calculation to be portable you need to store it as UTC and then when you display it convert to local time. As a general rule Store dates as UTC and convert to local time for presentation.

    0 讨论(0)
  • 2020-12-01 07:51

    How about something like this?

        TimeSpan diff = dateTimeNew - dateTimeOld;
        string output = string.Format("{0} days, {1} hours, {2} minues, {3} seconds", diff.Days, diff.Hours, diff.Minutes, diff.Seconds);
        Console.WriteLine(output);
    
    0 讨论(0)
  • 2020-12-01 07:54
        DateTime myDay = DateTime.Now;
        DateTime otherDate = DateTime.Now.AddYears(1);
        var test = otherDate.Subtract(myDay);
        Console.WriteLine("Days:" + test.Days + "Hours:" + test.Hours +"Minutes" +  test.Minutes +"Seconds" + test.Seconds);
    

    Here test is of type TimeStamp

    0 讨论(0)
提交回复
热议问题