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条回答
Fickle 薄情
2楼-- · 2019-01-07 03:33
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

查看更多
放我归山
3楼-- · 2019-01-07 03:33

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;
查看更多
我命由我不由天
4楼-- · 2019-01-07 03:34

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.

查看更多
戒情不戒烟
5楼-- · 2019-01-07 03:34

Try this one

var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;
查看更多
混吃等死
6楼-- · 2019-01-07 03:35

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");
查看更多
祖国的老花朵
7楼-- · 2019-01-07 03:35

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");
查看更多
登录 后发表回答