如何仅更改DateTime的日期部分,同时保留时间部分? [英] How to change only the date portion of a DateTime, while keeping the time portion?
本文介绍了如何仅更改DateTime的日期部分,同时保留时间部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在代码中使用了许多DateTime。我想将那些DateTimes更改为我的特定日期,并保留
时间。
I use many DateTime in my code. I want to change those DateTimes to my specific date and keep time.
1. "2012/02/02 06:00:00" => "2015/12/12 : 06:00:00"
2. "2013/02/02 12:00:00" => "2015/12/12 : 12:00:00"
我使用此样式进行更改,但是
I use this style to change, but it seem not the good way and I want to ask have any way to achieve this task.
DateTime newDateTime = new DateTime(2015,12,12,oldDateTime.Hour,oldDateTime.Minute,0);
推荐答案
根据您提供的信息,我认为这种方法很好如果要避免经常重写 oldDateTime.Hour,oldDateTime.Minute,0
片段,则可以创建自己的静态类以简化方法调用。
With the information you have given, I think this method is fine. If you want to avoid rewriting the oldDateTime.Hour,oldDateTime.Minute,0
piece often, you could create your own static class to simplify the method calls.
在您的常规应用中:
class Program
{
static void Main(string[] args)
{
DateTime time = DateTime.Now;
DateTime newDateTime = MyDateTimeUtil.CreateDateFromTime(2015, 12, 12, time);
}
}
创建 DateTime
值:
public static class MyDateTimeUtil
{
public static DateTime CreateDateFromTime(int year, int month, int day, DateTime time)
{
return new DateTime(year, month, day, time.Hour, time.Minute, 0);
}
}
这篇关于如何仅更改DateTime的日期部分,同时保留时间部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文