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条回答
Lonely孤独者°
2楼-- · 2019-01-07 03:10

You can't change a DateTime value - it's immutable. However, you can change the variable to have a new value. The easiest way of doing that to change just the time is to create a TimeSpan with the relevant time, and use the DateTime.Date property:

DateTime s = ...;
TimeSpan ts = new TimeSpan(10, 30, 0);
s = s.Date + ts;

s will now be the same date, but at 10.30am.

Note that DateTime disregards daylight saving time transitions, representing "naive" Gregorian time in both directions (see Remarks section in the DateTime docs). The only exceptions are .Now and .Today: they retrieve current system time which reflects these events as they occur.

This is the kind of thing which motivated me to start the Noda Time project, which is now production-ready. Its ZonedDateTime type is made "aware" by linking it to a tz database entry.

查看更多
女痞
3楼-- · 2019-01-07 03:10

Adding .Date to your date sets it to midnight (00:00).

MyDate.Date

Note The equivavalent SQL is CONVERT(DATETIME, CONVERT(DATE, @MyDate))

What makes this method so good is that it's both quick to type and easy to read. A bonus is that there is no conversion from strings.

I.e. To set today's date to 23:30, use:

DateTime.Now.Date.AddHours(23).AddMinutes(30)

You can of course replace DateTime.Now or MyDate with any date of your choice.

查看更多
成全新的幸福
4楼-- · 2019-01-07 03:11

DateTime is an immutable type, so you can't change it.

However, you can create a new DateTime instance based on your previous instance. In your case, it sounds like you need the Date property, and you can then add a TimeSpan that represents the time of day.

Something like this:

var newDt = s.Date + TimeSpan.FromHours(2);
查看更多
甜甜的少女心
5楼-- · 2019-01-07 03:13
int year = 2012;
int month = 12;
int day = 24;
int hour = 0;
int min = 0;
int second = 23;
DateTime dt = new DateTime(year, month, day, hour, min, second);
查看更多
Summer. ? 凉城
6楼-- · 2019-01-07 03:14
s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);

In this way you preserve your date, while inserting a new hours, minutes and seconds part to your liking.

查看更多
Evening l夕情丶
7楼-- · 2019-01-07 03:14

one liner

var date = DateTime.Now.Date.Add(new TimeSpan(4, 30, 0));

would bring back todays date with a time of 4:30:00, replace DateTime.Now with any date object

查看更多
登录 后发表回答