Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change time in DateTime?

Tags:

c#

datetime

time

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

DateTime s = some datetime; 
like image 402
Santhosh Avatar asked Dec 07 '09 10:12

Santhosh


People also ask

How do you declare an hour in Python?

Yes, just do date = datetime. strptime('26 Sep 2012', '%d %b %Y'). replace(hour=11, minute=59) .


2 Answers

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.

like image 116
Jon Skeet Avatar answered Sep 28 '22 22:09

Jon Skeet


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); 
like image 29
joshcomley Avatar answered Sep 28 '22 22:09

joshcomley