有没有更好的方法来修剪DateTime到一个特定的精度?

编程入门 行业动态 更新时间:2024-10-14 20:25:45
本文介绍了有没有更好的方法来修剪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到一个特定的精度?

本文发布于:2023-11-23 18:56:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法来   精度   DateTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!