简体   繁体   中英

How to change only the date portion of a DateTime, while keeping the time portion?

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);

A better way that preserves the seconds, milliseconds and smaller parts of the time would be:

DateTime newDateTime = new DateTime(2015,12,12) + oldDateTime.TimeOfDay;

Or you could make an extension method to apply a new Date to an existing DateTime and, at the same time, not trust the new date to be without a TimeOfDay on it:-

public static DateTime WithDate (this DateTime datetime, DateTime newDate)
{
   return newDate.Date + datetime.TimeOfDay;
}

IMHO DateTime is one of the weakest parts of .NET. For example, a TimeSpan is not the same as a TimeOfDay nor can it represent a 'TimePeriod' (in months) - these are three separate concepts and mixing them up was a poor choice. Moving to DateTimeOffset is generally preferred or to the excellent Noda time library.

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.

In your regular application:

class Program
{
    static void Main(string[] args)
    {
        DateTime time = DateTime.Now;
        DateTime newDateTime = MyDateTimeUtil.CreateDateFromTime(2015, 12, 12, time);
    }
}

The static class that creates the DateTime value:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM