Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate milliseconds off of a .NET DateTime

Tags:

c#

.net

datetime

I'm trying to compare a time stamp from an incoming request to a database stored value. SQL Server of course keeps some precision of milliseconds on the time, and when read into a .NET DateTime, it includes those milliseconds. The incoming request to the system, however, does not offer that precision, so I need to simply drop the milliseconds.

I feel like I'm missing something obvious, but I haven't found an elegant way to do it (C#).

like image 669
Jeff Putz Avatar asked Jun 17 '09 01:06

Jeff Putz


People also ask

How do I remove seconds from DateTime?

Solution 1 Using different methods on the DateTime, like . Today give the date part, but the other parts of it are zero. This is by design. If you don't want to display the seconds when you create the string, use a format string, like MM/dd/yyyy hh.mm and leave the tt part off.

How precise is DateTime now?

From MSDN you'll find that DateTime. Now has an approximate resolution of 10 milliseconds on all NT operating systems. The actual precision is hardware dependent.

How do I get microseconds in C#?

To convert a number of ticks to microseconds, just use: long microseconds = ticks / (TimeSpan. TicksPerMillisecond / 1000);


1 Answers

The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).

DateTime dateTime = ... anything ... dateTime = new DateTime(     dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond),      dateTime.Kind     ); 

or the equivalent and shorter:

dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond)); 

This could be generalized into an extension method:

public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan) {     if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException     if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values     return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks)); } 

which is used as follows:

dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute ... 
like image 64
Joe Avatar answered Oct 05 '22 20:10

Joe