How to change time in DateTime?

2019-01-07 02:50发布

How can I change only the time in my DateTime variable "s"?

DateTime s = some datetime;

标签: c# datetime time
27条回答
你好瞎i
2楼-- · 2019-01-07 03:35

Doesn't that fix your problems??

Dateime dt = DateTime.Now;
dt = dt.AddSeconds(10);
查看更多
三岁会撩人
3楼-- · 2019-01-07 03:36

Here is a method you could use to do it for you, use it like this

DateTime newDataTime = ChangeDateTimePart(oldDateTime, DateTimePart.Seconds, 0);

Here is the method, there is probably a better way, but I just whipped this up:

public enum DateTimePart { Years, Months, Days, Hours, Minutes, Seconds };
public DateTime ChangeDateTimePart(DateTime dt, DateTimePart part, int newValue)
{
    return new DateTime(
        part == DateTimePart.Years ? newValue : dt.Year,
        part == DateTimePart.Months ? newValue : dt.Month,
        part == DateTimePart.Days ? newValue : dt.Day,
        part == DateTimePart.Hours ? newValue : dt.Hour,
        part == DateTimePart.Minutes ? newValue : dt.Minute,
        part == DateTimePart.Seconds ? newValue : dt.Second
        );
}
查看更多
倾城 Initia
4楼-- · 2019-01-07 03:36
//The fastest way to copy time            

DateTime justDate = new DateTime(2011, 1, 1); // 1/1/2011 12:00:00AM the date you will be adding time to, time ticks = 0
DateTime timeSource = new DateTime(1999, 2, 4, 10, 15, 30); // 2/4/1999 10:15:30AM - time tick = x

justDate = new DateTime(justDate.Date.Ticks + timeSource.TimeOfDay.Ticks);

Console.WriteLine(justDate); // 1/1/2011 10:15:30AM
Console.Read();
查看更多
登录 后发表回答