0

I take two object from database. One is a filename with date init and second one is a DateTime object like 2021-08-08 17:32:07.880.

First, I converted filename to datetime with the code shown here:

var fileDate = DateTime.ParseExact(filename, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

I have to check that the difference between the first date and the second date is 3 hours 15 min or simply 3 hours.

How do I delete seconds and milliseconds of date 2, and compare them?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
kkami-sama
  • 15
  • 6

2 Answers2

3

I'd go similar to MatJ's recommendation:

You've got your file time, and your DB time, which might have seconds and milliseconds on it. If you do the later one minus the earlier one you get a timespan representing the length of time between the datetimes

dBDate - fileDate

Timespans have a TotalMinutes property that is a decimal. A timespan of 5 minutes 45 seconds would have a TotalMinutes of 5.75

So, if we cast that to an int it cuts off the seconds; simples!

var t = (int)((dBDate - fileDate).TotalMinutes);

Now you can compare your t for equality to 180 (3h) or 195 (3h15h

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
1

It is very easy to do !

Try following code :

TimeSpan timeSpan = (firstDate - secondDate)
timeSpan.CompareTo(new TimeSpan(3, 15, 0)) // hrs, mins, seconds

This CompareTo method will return 1 if difference between two times is greater than 3 hrs and 15 mins, otherwise, it will return -1

PS: firstDate and secondDate are in DateTime

  • I am going to try this ty!! But um should i use any Math function like abs or smth else? – kkami-sama Aug 08 '21 at 18:05
  • @kkami-sama if it works for you, don't forget to upvote and accept the answer – Shreekesh Murkar Aug 08 '21 at 18:25
  • 1
    @kkami-sama Substracting to dates gives you a TimeSpan structure. So you may take the [Duration](https://learn.microsoft.com/en-us/dotnet/api/system.timespan.duration?view=net-5.0) method which gives you a new TimeSpan whose value is the absolute value of the current TimeSpan. So something like `(date1 - date2).Duration().TotalMinutes` And note the difference between Minutes and TotalMinutes - you will the latter one. – Steeeve Aug 08 '21 at 19:03