Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to trim a DateTime to a specific precision? [duplicate]

Tags:

c#

.net

datetime

What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this?

private static DateTime TrimDateToMinute(DateTime date) {     return new DateTime(         date.Year,          date.Month,          date.Day,          date.Hour,          date.Minute,          0); } 

What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.

like image 803
Lloyd Cotten Avatar asked Sep 30 '08 12:09

Lloyd Cotten


People also ask

How do I cut a datetime from a date in python?

To remove the time from a datetime object in Python, convert the datetime to a date using date(). You can also use strftime() to create a string from a datetime object without the time.

How do I round a date in C#?

Round(new TimeSpan(1,0,0)); DateTime minuteCeiling = DateTime. Now. Ceil(new TimeSpan(0,1,0)); DateTime weekFloor = DateTime. Now.

What is the format of datetime?

For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".


2 Answers

static class Program {     //using extension method:     static DateTime Trim(this DateTime date, long roundTicks)     {         return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind);     }      //sample usage:     static void Main(string[] args)     {         Console.WriteLine(DateTime.Now);         Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay));         Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour));         Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond));         Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute));         Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond));         Console.ReadLine();     }  } 
like image 93
Bartek Szabat Avatar answered Sep 18 '22 02:09

Bartek Szabat


You could use an enumeration

public enum DateTimePrecision {   Hour, Minute, Second }  public static DateTime TrimDate(DateTime date, DateTimePrecision precision) {   switch (precision)   {     case DateTimePrecision.Hour:       return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);     case DateTimePrecision.Minute:       return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0);     case DateTimePrecision.Second:       return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);     default:       break;   } } 

and expand as required.

like image 34
Rikalous Avatar answered Sep 21 '22 02:09

Rikalous