Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime convert to Date and then back to DateTime in C#

I use this to convert DateTime value into Date and then I add 00:00:00 and 23:59:59 to make sure whole day is taken into consideration when counting stuff. I'm pretty sure it's wrong way of doing things. What would be the right way?

        DateTime varObliczOd = DateTime.Parse(dateTimeWycenaPortfelaObliczDataOd.Value.ToShortDateString() + " 00:00:00");
        DateTime varObliczDo = DateTime.Parse(dateTimeWycenaPortfelaObliczDataDo.Value.ToShortDateString() + " 23:59:59");
like image 459
MadBoy Avatar asked Nov 30 '22 18:11

MadBoy


2 Answers

if dateTimeWycenaPortfelaObliczDataOd is of type DateTime, You can use:

dateTimeWycenaPortfelaObliczDataOd.Date

to get the date part only (time will be 00:00:00...). If you want to get the very last tick of the date, you can use:

dateTimeWycenaPortfelaObliczDataOd.Date.AddDays(1).AddTicks(-1)

but you really better work with the next date (.AddDays(1)).

In any case, there is no need to convert to string and back to DateTime.

like image 139
M.A. Hanin Avatar answered Dec 05 '22 20:12

M.A. Hanin


DateTime objects have a Date property which might be what you need.

like image 28
Software.Developer Avatar answered Dec 05 '22 20:12

Software.Developer