有没有更好的方法来修剪DateTime到一个特定的精度? [英] Is there a better way to trim a DateTime to a specific precision?

查看:98
本文介绍了有没有更好的方法来修剪DateTime到一个特定的精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将DateTime对象修剪到特定精度的最佳方法是什么?例如,如果我有一个值为'2008-09-29 09:41:43'的DateTime,但是我只想要精确到这一刻,有没有比这更好的方法? p>

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.

推荐答案

static class Program
{
    //using extension method:
    static DateTime Trim(this DateTime date, long roundTicks)
    {
        return new DateTime(date.Ticks - date.Ticks % roundTicks);
    }

    //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();
    }

}

这篇关于有没有更好的方法来修剪DateTime到一个特定的精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆