## 5 replies

Last post Jun 12, 2019 08:26 AM by kaarthikeyan

• kaarthikeyan

None

0 Points

24 Posts

### DateTime calculation in c#

Hi,

I have javascript code which have datetime calculation. There  i'm using moment js framework to calculate. The same logic i need to implement in c#. Could any one help on this.

const today = new Date();
const ModifiedTime = moment(this.ModifiedDate);
const TimelineCal = moment.duration(moment(today).diff(ModifiedTime )).asHours();

• Mikesdotnett...

All-Star

190604 Points

27668 Posts

Moderator

### Re: DateTime calculation in c#

#### kaarthikeyan

The same logic i need to implement in c#.
What logic? What does that js code actually do?

• kaarthikeyan

None

0 Points

24 Posts

### Re: DateTime calculation in c#

Js code return the hours.

• kaarthikeyan

None

0 Points

24 Posts

### Re: DateTime calculation in c#

Difference b/w todays datetime and modified datetime.

Participant

810 Points

495 Posts

### Re: DateTime calculation in c#

Hello Kaarthikeyan,

According to your previous questions , I understood that you want to find time difference between two dates in c#

Try with this,

``````var dateOne = DateTime.Now;
var diff = dateTwo.Subtract(dateOne);
var res = String.Format("{0}:{1}:{2}", diff.Hours,diff.Minutes,diff.Seconds));``````

or else you can use Timespan two find out difference .

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.

``TimeSpan diff = dateTime1 - dateTime2``
`int totalHours = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).Hours);`
```TimeSpan ts = EndDate - StartDate;

// Difference in days.

int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double

// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double

// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double```

There are various methods for getting the days, hours, minutes, seconds and milliseconds back from this structure.

If you are just interested in the difference then:

`TimeSpan diff = Math.Abs(dateTime1 - dateTime2);`

will give you the positive difference between the times regardless of the order.

If you have just got the time component but the times could be split by midnight then you need to add 24 hours to the span to get the actual difference:

```TimeSpan diff = dateTime1 - dateTime2;
if (diff < 0)
{
diff = diff + TimeSpan.FromDays(1);
}```

Thank you

Ashish Jain
• kaarthikeyan

None

0 Points

24 Posts