Coder Perfect

What is the best way to modify the time in DateTime?

Problem

In my DateTime variable “s,” how can I alter only the time?

DateTime s = some datetime;

Asked by Santhosh

Solution #1

A DateTime value is immutable, thus you can’t change it. You can, however, modify the variable’s value to anything else. To alter only the time, the simplest method is to create a TimeSpan with the required time and utilize the DateTime. Property of the date:

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

It will now take place on the same day, but at 10.30 a.m.

DateTime ignores daylight saving time changes in both directions, signifying “naive” Gregorian time (see Remarks section in the DateTime docs). There are only a few exceptions. Now and then. Today: they get the current system time, which reflects the current occurrences.

This is the type of thing that inspired me to launch the Noda Time project, which is now ready for production. By tying its ZonedDateTime type to a tz database entry, it becomes “aware.”

Answered by Jon Skeet

Solution #2

Okay, I’ll jump right in with a suggestion for an extension method:

public static DateTime ChangeTime(this DateTime dateTime, int hours, int minutes, int seconds, int milliseconds)
{
    return new DateTime(
        dateTime.Year,
        dateTime.Month,
        dateTime.Day,
        hours,
        minutes,
        seconds,
        milliseconds,
        dateTime.Kind);
}

Then call:

DateTime myDate = DateTime.Now.ChangeTime(10,10,10,0);

It’s worth noting that this extension creates a new date object, so you can’t perform anything like this:

DateTime myDate = DateTime.Now;
myDate.ChangeTime(10,10,10,0);

But you can do this:

DateTime myDate = DateTime.Now;
myDate = myDate.ChangeTime(10,10,10,0);

Answered by joshcomley

Solution #3

s = s.Date.AddHours(x).AddMinutes(y).AddSeconds(z);

You can keep your date while adding a new hours, minutes, and seconds section to your liking.

Answered by Webleeuw

Solution #4

one liner

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

would replace DateTime with today’s date and a time of 4:30:00. Now you may use any date object.

Answered by Carl Woodhouse

Solution #5

You can’t modify a DateTime because it’s an immutable type.

You can, however, make a new DateTime instance based on the existing one. In your example, it appears that the Date property is required, after which you can add a TimeSpan to reflect the time of day.

Something like this:

var newDt = s.Date + TimeSpan.FromHours(2);

Answered by Mark Seemann

Post is based on https://stackoverflow.com/questions/1859248/how-to-change-time-in-datetime