Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set only time part of a DateTime variable in C# [duplicate]

Tags:

c#

.net

datetime

I have a DateTime variable:

DateTime date = DateTime.Now; 

I want to change the time part of a DateTime variable. But when I tried to access time part (hh:mm:ss) these fields are readonly.

Can't I set these properties?

like image 338
Vaibhav Jain Avatar asked Nov 23 '10 14:11

Vaibhav Jain


People also ask

How do you assign a value to a DateTime variable?

There are two ways to initialize the DateTime variable: DateTime DT = new DateTime();// this will initialze variable with a date(01/01/0001) and time(00:00:00). DateTime DT = new DateTime(2019,05,09,9,15,0);// this will initialize variable with a specific date(09/05/2019) and time(9:15:00).


2 Answers

Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:

var dateNow = DateTime.Now; var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6); 
like image 143
Ahmad Mageed Avatar answered Oct 17 '22 07:10

Ahmad Mageed


you can't change the DateTime object, it's immutable. However, you can set it to a new value, for example:

var newDate = oldDate.Date + new TimeSpan(11, 30, 55); 
like image 20
Daniel Perez Avatar answered Oct 17 '22 06:10

Daniel Perez