0

I want to insert just year : month : day for a specific column in a database table row, but my variable is of DateTime Type.

To remove milliseconds I just used following code:

DateTime createdate = System.DateTime.Now;
createdate = createdate.AddTicks(-(createdate.Ticks % TimeSpan.TicksPerSecond));

How to remove hours, minutes, seconds from this?

2
  • 1
    What database and what is the datatype of the column that you want to set?
    – Steve
    Jan 25, 2016 at 7:52
  • 1
    By the way, you mean year : month : day instead of year : month : date, right? Jan 25, 2016 at 7:54

2 Answers 2

6

You can use .Date property which set's the time part to midnight.

DateTime justDate = createdate.Date;

or you can use DateTime.Today which generates the same result for DateTime.Now.Date value.

DateTime justDate = DateTime.Today;

If you use SQL Server, date type is mapped with DateTime on CLR side which you can safely insert that value.

3
  • It's also worth adding that, if it is the current date you want, then you can use DateTime.Today, which is conceptually the same as DateTime.Now.Date Jan 25, 2016 at 8:12
  • @christophano Yeap, added that as well. Thanks. Jan 25, 2016 at 8:15
  • Not that performance is an issue here, but DateTime.Today is conceivably more performant than DateTime.Now.Date, but even if it weren't, preferring abstraction is always best practice.
    – Neil
    Jan 25, 2016 at 8:19
0

Use the Date property on your createdate variable to return just the date component without the time component.

DateTime createdate = System.DateTime.Now;
createdate = createdate.AddTicks(-(createdate.Ticks % TimeSpan.TicksPerSecond));
var dateOnly = createdate.Date;

Note you will still have the time in the object, set to 00:00:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.