-1

I organized a program which started on 31st December 2018 at 10:00pm hence its been four months ago, i want a way to find this duration by code.

for example , how youtube is able to tell when a comment was written(eg,4years ago,5 months ago).

LBG
  • 51
  • 2
  • 8
  • You are looking for [TimeSpan](https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=netframework-4.8) – Filburt Apr 26 '19 at 11:07
  • What should happen to this calculation if you stop and restart the program? Do you want to know the uptime from the last start of your program? – Steve Apr 26 '19 at 11:13
  • maybe this is what you should be looking at. This SO question looks for duration in years, months, days etc. just how you have given the example of youtube. https://stackoverflow.com/questions/4638993/difference-in-months-between-two-dates – akg179 Apr 26 '19 at 11:26

3 Answers3

1

You can simply substract a DateTime object from another, which results in a TimeSpan representing the difference:

DateTime x = DateTime.Now;
DateTime y = DateTime.Today;
TimeSpan difference = x - y; 
Rik
  • 28,507
  • 14
  • 48
  • 67
1
        var programStartDateTime = new DateTime(2018, 12, 31);
        var timeSpan = DateTime.Now - programStartDateTime;
        Console.WriteLine($"The difference is: {timeSpan.ToString()}");
Jonatan Dragon
  • 4,675
  • 3
  • 30
  • 38
0

I think below sample code may help you

  DateTime date1 = DateTime.Now;
  DateTime date2 = DateTime.Now.AddDays(-1);
  TimeSpan time = date1 - date2;
  WriteLine($"TimeSpan : {time}" );
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32