Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to truncate DateTime in C#?

Tags:

c#

Assume I have a DateTime:

    DateTime datetime(2013,11,08,17,45,23,300);//2013:11:08 17:45:23:300

I want to truncate this DateTime by differenct accuracy and return the minimum DateTime like this:

    Year:         2013:01:01 00:00:00:000      
    Quarter:      2013:10:01 00:00:00:000    //Oct is first month of that quarter 
    Month:        2013:11:01 00:00:00:000
    Week:         2013:11:03 00:00:00:000    // 3rd is Sunday of that week
    Day:          2013:11:08 00:00:00:000
    Hours         2013:11:08 17:00:00:000   
    Minute:       2013:11:08 17:45:00:000   
    Second:       2013:11:08 17:45:23:000   

I know you can do it by changing different part of the DateTime, is there a better way to do it? or is there already a build in function in .net which I don't know?

like image 873
www.diwatu.com Avatar asked Nov 02 '25 11:11

www.diwatu.com


1 Answers

There's not one that I know of, but this should do the trick:

public enum Accuracy { Year, Quarter, Month, Week, Day, Hour, Minute, Second};

private static DateTime TruncateDate(DateTime inDate, Accuracy accuracy){
        switch (accuracy)
        {
            case Accuracy.Year:
                return new DateTime(inDate.Year, 1, 1);
            case Accuracy.Quarter:
                int i = inDate.Month % 3;
                return new DateTime(inDate.Year, inDate.Month - i + 1, 1);
            case Accuracy.Month:
                return new DateTime(inDate.Year, inDate.Month, 1);
            case Accuracy.Week:
                return new DateTime(inDate.Year, inDate.Month, inDate.Day).AddDays(-(int)inDate.DayOfWeek);
            case Accuracy.Day:
                return new DateTime(inDate.Year, inDate.Month, inDate.Day);
            case Accuracy.Hour:
                return new DateTime(inDate.Year, inDate.Month, inDate.Day, inDate.Hour, 0, 0);
            case Accuracy.Minute:
                return new DateTime(inDate.Year, inDate.Month, inDate.Day, inDate.Hour, inDate.Minute, 0);
            case Accuracy.Second:
                return new DateTime(inDate.Year, inDate.Month, inDate.Day, inDate.Hour, inDate.Minute, inDate.Second);
            default:
                throw new ArgumentOutOfRangeException("accuracy");
        }
    }

Edit: corrected for when Sunday is in a different month.

like image 189
Xinbi Avatar answered Nov 04 '25 01:11

Xinbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!