450

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

DateTime s = some datetime;
Mr Rubix
  • 1,492
  • 14
  • 27
Santhosh
  • 19,616
  • 22
  • 63
  • 74

29 Answers29

728

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.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 13
    s.Date.Add(new TimeSpan(0, 0, 0)) should also work. Using it to null out time when checking between days. – Yogurt The Wise Mar 14 '12 at 13:49
  • 12
    @user295734: Why would you call `Add` providing a zero timespan? Your expression is equivalent to `s.Date`, but longer... – Jon Skeet Mar 14 '12 at 14:21
  • Forgot to correct it, realized it after i put it in the code, for setting to zero(what i was originally searching for). But i was just trying to show how to get a time set in one line, if not setting to 0. – Yogurt The Wise Mar 14 '12 at 14:44
  • 4
    If you have 2 `DateTime`s, (one for the date and one for the time) you can do this: `var result = date.Date + time.TimeOfDay;` – Zachary Yates Apr 23 '13 at 20:09
  • 2
    @ZacharyYates: Yes, although I'd argue that at that point your model is broken to start with, and `time` shouldn't be a `DateTime`. (I'd use Noda Time of course, but...) – Jon Skeet Apr 23 '13 at 20:13
  • 1
    @JonSkeet Agreed. Just pointing it out if someone has to work with a model that they can't change (like I did earlier today) – Zachary Yates Apr 23 '13 at 21:30
137

Alright I'm diving in with my suggestion, 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 important to note that this extension returns a new date object, so you can't do 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);
joshcomley
  • 28,099
  • 24
  • 107
  • 147
  • 7
    This is essentially the same as `Datetime.Today.Add(time.TimeOfDay)`. That's because internally, the constructor doesn't do any calendar-based corrections except accounting for a leap year for the date part. I.e. `DateTime` is a "naive" implementation in terms of Python's `datetime` module. – ivan_pozdeev Oct 08 '14 at 11:54
85
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.

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
Webleeuw
  • 7,222
  • 33
  • 34
  • @Webleeuw Of course, a remote possibility of an [ArgumentOutOfRangeException](http://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception.aspx) depending upon the added values. Here's a [Pex](http://pexforfun.com/default.aspx?language=CSharp&sample=Y2k) puzzle that demonstrate this. – lifebalance Oct 31 '13 at 16:03
  • And depending on the use case, can also do `.AddMilliseconds()` if needed. – Broots Waymb Apr 21 '17 at 16:15
  • @lifebalance the Pex link no longer works, could you elaborate the problem? – Benni Aug 09 '21 at 09:41
55

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

Carl Woodhouse
  • 777
  • 6
  • 6
26

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);
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
22

If you already have the time stored in another DateTime object you can use the Add method.

DateTime dateToUse = DateTime.Now();
DateTime timeToUse = new DateTime(2012, 2, 4, 10, 15, 30); //10:15:30 AM

DateTime dateWithRightTime = dateToUse.Date.Add(timeToUse.TimeOfDay);

The TimeOfDay property is a TimeSpan object and can be passed to the Add method. And since we use the Date property of the dateToUse variable we get just the date and add the time span.

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
ShaneA
  • 1,325
  • 10
  • 18
21

Simplest solution :

DateTime s = //some Datetime that you want to change time for 8:36:44 ;
s = new DateTime(s.Year, s.Month, s.Day, 8, 36, 44);

And if you need a specific Date and Time Format :

s = new DateTime(s.Year, s.Month, s.Day, 8, 36, 44).ToString("yyyy-MM-dd h:mm:ss");
Mr Rubix
  • 1,492
  • 14
  • 27
17

You can assign an initial value to a new DateTime value in many different ways:

  • Extension Method

Extension method DateTime

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

then using ChangeTime:

    DateTime datetime = DateTime.Now; //Your DateTime
    datetime = datetime.ChangeTime(12, 20, 10);
  • using the Add methods

    DateTime datetime = DateTime.Now; //Your DateTime
    datetime = datetime.Date.AddHours(12).AddMinutes(20).AddSeconds(10);
    
  • using the Timespan

    DateTime datetime = DateTime.Now; //Your DateTime
    datetime = datetime.Date.Add(new TimeSpan(12, 20, 10));
    
  • using initial value

    DateTime datetime = DateTime.Now;
    datetime = new DateTime(datetime.Year, datetime.Month, datetime.Day, 12, 20, 10);
    
Reza Jenabi
  • 3,884
  • 1
  • 29
  • 34
  • nice extension method – Sras Apr 12 '21 at 02:52
  • I was going to say "nice changetime() example :)" but DateTime has no ChangeTime method that I can find :( Oh I see, you provided your own!! OK , fair enough :) Pity Microsoft didn't pull their finger out and provide something for setting time of day. – Zeek2 Mar 07 '23 at 14:57
13
DateTime ts = DateTime.Now;
ts = new DateTime ( ts.Year, ts.Month, ts.Day, 0, 0, 0 ) ;
Console.WriteLine ( "Today = " + ts.ToString("M/dd/yy HH:mm:ss") ) ;

Executed: Today = 9/04/15 00:00:00

philip
  • 131
  • 2
  • 4
8

Happened upon this post as I was looking for the same functionality this could possibly do what the guy wanted. Take the original date and replace the time part

DateTime dayOpen = DateTime.Parse(processDay.ToShortDateString() + " 05:00 AM");
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
BlackLarry
  • 81
  • 1
  • 1
7

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.

WonderWorker
  • 8,539
  • 4
  • 63
  • 74
  • Thanks for clarifying the importance of `.Date`! For whatever reason I didn't really grasp why that was needed when I read the accepted answer. – Cliabhach Sep 11 '22 at 22:53
  • Best and cleanest answer. Upvoted and thumbed up – Lukas Apr 05 '23 at 20:13
5

Since DateTime is immutable, a new instance has to be created when a date component needs to be changed. Unfortunately, there is no built-in functionality to set individual components of a DateTime instance.

Using the following extension methods

public static DateTime SetPart(this DateTime dateTime, int? year, int? month, int? day, int? hour, int? minute, int? second)
{
    return new DateTime(
        year ?? dateTime.Year,
        month ?? dateTime.Month,
        day ?? dateTime.Day,
        hour ?? dateTime.Hour,
        minute ?? dateTime.Minute,
        second ?? dateTime.Second
    );
}

public static DateTime SetYear(this DateTime dateTime, int year)
{
    return dateTime.SetPart(year, null, null, null, null, null);
}

public static DateTime SetMonth(this DateTime dateTime, int month)
{
    return dateTime.SetPart(null, month, null, null, null, null);
}

public static DateTime SetDay(this DateTime dateTime, int day)
{
    return dateTime.SetPart(null, null, day, null, null, null);
}

public static DateTime SetHour(this DateTime dateTime, int hour)
{
    return dateTime.SetPart(null, null, null, hour, null, null);
}

public static DateTime SetMinute(this DateTime dateTime, int minute)
{
    return dateTime.SetPart(null, null, null, null, minute, null);
}

public static DateTime SetSecond(this DateTime dateTime, int second)
{
    return dateTime.SetPart(null, null, null, null, null, second);
}

you can set individual DateTime components like

var now = DateTime.Now;

now.SetSecond(0);
solidsparrow
  • 51
  • 1
  • 2
4

When you construct your DateTime object, use a constructor that allows you to specify time:

var myDateTime = new DateTime(2000, 01, 01, 13, 37, 42);  // 2000-01-01 13:37:42

If you already have a DateTime object and wish to change the time, uou can add minutes, hours or seconds to your DateTime using simple methods:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime = myDateTime.AddHours(13);                     // 2000-01-01 13:00:00
myDateTime = myDateTime.AddMinutes(37);                   // 2000-01-01 13:37:00
myDateTime = myDateTime.AddSecounds(42);                  // 2000-01-01 13:37:42

Notice how we have to "save" the result from each method call to the myDateTime variable. This is because the DateTime is immutable, and its methods simply create new instances with the extra hours/minutes/seconds added.

If you need to add both hours and minutes (and/or seconds) and the same time, you can simplify the code by adding a TimeSpan to the original DateTime instead:

var myDateTime = new DateTime(2000, 01, 01);              // 2000-01-01 00:00:00
myDateTime += new TimeSpan(13, 37, 42);                   // 2000-01-01 13:37:42

If you want to set absolute hours/minues/seconds, rather than adding to the existing values, you can use the aforementioned DateTime constructor, and reuse values for year/month/day from earlier:

myDateTime = new DateTime(myDateTime.Year, myDateTime.Month, myDateTime.Day,
                          20, 33, 19)                     // 2000-01-01 20:33:19
Jørn Schou-Rode
  • 37,718
  • 15
  • 88
  • 122
4

In fact, you can't change the time once it's created. But you can create it easily with many constructors: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.7.2

For example, if you want to create a DateTime changing Seconds, you can just do this:

DateTime now = DateTime.Now;
DateTime secondschanged = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, yourseconds);
Francesc MP
  • 133
  • 5
3

If you have a DateTime like 2014/02/05 18:19:51 and want just 2014/02/05, you can do that:

_yourDateTime = new DateTime(_yourDateTime.Year, _yourDateTime.Month, _yourDateTime.Day)
3

Use Date.Add and add a New TimeSpan with the new time you want to add

DateTime dt = DateTime.Now
dt.Date.Add(new TimeSpan(12,15,00))
3

To set end of a day:

date = new DateTime(date.Year, date.Month, date.Day, 23, 59, 59);
Kamil
  • 782
  • 1
  • 9
  • 24
2
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);
Sagar Rawal
  • 1,442
  • 2
  • 12
  • 39
1

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
        );
}
naspinski
  • 34,020
  • 36
  • 111
  • 167
1

I have just come across this post because I had a similar issue whereby I wanted to set the time for an Entity Framework object in MVC that gets the date from a view (datepicker) so the time component is 00:00:00 but I need it to be the current time. Based on the answers in this post I came up with:

myEntity.FromDate += DateTime.Now.TimeOfDay;
Rob
  • 10,004
  • 5
  • 61
  • 91
1
//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();
stealthyninja
  • 10,343
  • 11
  • 51
  • 59
Pawel Cioch
  • 2,895
  • 1
  • 30
  • 29
0

I prefer this:

DateTime s = //get some datetime;
s = new DateTime(s.Year, s.Month,s.Day,s.Hour,s.Minute,0);
Java Devil
  • 10,629
  • 7
  • 33
  • 48
andrew
  • 19
  • 1
0
  DateTime s;
//s = datevalue
                s = s.AddMilliseconds(10);
                s = s.AddMinutes(10);
                s = s.AddSeconds(10);
                s = s.AddHours(10);

you could add +ve/-ve values in parameter.

s.Add(new TimeSpan(1, 1, 1));
Saar
  • 8,286
  • 5
  • 30
  • 32
  • @Jon: I commented the line. the user need to assign some value before using this code. – Saar Dec 07 '09 at 11:08
  • @Saar: More importantly, you've *now* added the assignments back to s (except for the call to s.Add(...)). – Jon Skeet Dec 07 '09 at 11:24
  • @Jon: I learned my lesson. Thanks for your kindness and time. I really mean it. – Saar Dec 07 '09 at 11:29
0

Doesn't that fix your problems??

Dateime dt = DateTime.Now;
dt = dt.AddSeconds(10);
Naveed Butt
  • 2,861
  • 6
  • 32
  • 55
0
 Using an extencion to DateTime:  

        public enum eTimeFragment
        {
            hours,
            minutes,
            seconds,
            milliseconds
        }
        public static DateTime ClearTimeFrom(this DateTime dateToClear, eTimeFragment etf)
        {
            DateTime dtRet = dateToClear;
            switch (etf)
            {
                case eTimeFragment.hours:
                    dtRet = dateToClear.Date;
                    break;
                case eTimeFragment.minutes:
                    dtRet = dateToClear.AddMinutes(dateToClear.Minute * -1);
                    dtRet = dtRet.ClearTimeFrom(eTimeFragment.seconds);
                    break;
                case eTimeFragment.seconds:
                    dtRet = dateToClear.AddSeconds(dateToClear.Second * -1);
                    dtRet = dtRet.ClearTimeFrom(eTimeFragment.milliseconds);
                    break;
                case eTimeFragment.milliseconds:
                    dtRet = dateToClear.AddMilliseconds(dateToClear.Millisecond * -1);
                    break;
            }
            return dtRet;

        }

Use like this:

Console.WriteLine (DateTime.Now.ClearTimeFrom(eTimeFragment.hours))

this has to return: 2016-06-06 00:00:00.000

Ricardo Figueiredo
  • 1,416
  • 13
  • 10
-1

Try this one

var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;
vicky
  • 1,546
  • 1
  • 18
  • 35
-2

The best solution is:

currdate.AddMilliseconds(currdate.Millisecond * -1).AddSeconds(currdate.Second * -1).AddMinutes(currdate.Minute * -1).AddHours(currdate.Hour * -1);
Arman H
  • 5,488
  • 10
  • 51
  • 76
Mahesh Alwani
  • 137
  • 3
  • 12
  • 1
    At first I thought this was wrong, but it makes sense *if* you assign the result to a DateTime object. It is not the best solution though. It requires you to know the current Time portion in order to make the correct calculations, while taking the Date portion of the date and adding there is the best. – ThunderGr Dec 09 '13 at 10:47
  • 1
    Definitely not "best". Far from readable and with repetitive usage of a magic number. – BartoszKP Oct 05 '15 at 14:04
-2

What's wrong with DateTime.AddSeconds method where you can add or substract seconds?

Chris Richner
  • 2,863
  • 2
  • 26
  • 38
  • 1
    Not only that, but it doesn't sound like it answers the question anyway. I suspect the OP wants a DateTime with the same date but a specific time - which would be *relatively* hard to do just using AddSeconds. – Jon Skeet Dec 07 '09 at 10:54
-5

here is a ghetto way, but it works :)

DateTime dt = DateTime.Now; //get a DateTime variable for the example
string newSecondsValue = "00";
dt = Convert.ToDateTime(dt.ToString("MM/dd/yyyy hh:mm:" + newSecondsValue));
naspinski
  • 34,020
  • 36
  • 111
  • 167
  • Another ghetto way but a bit cleaner would be to just play with the seconds. e.g. `dt.AddSeconds(0-dt.Seconds).AddSeconds(newSecondsValue)` but wouldn't recommend it. – mike Dec 07 '09 at 11:06