'How to set time to Zeros in DateTime?

Lets say I have the following DateTime variable

DateTime CurDate = '26/3/2014 12:00:00 AM';

I'm wondering how can I set the CurDate so that the value will become 26/3/2014 00:00:00 AM

Note that I still want the time, but with all zeros.

**P/S: The reason for having all zeros is because the datetime value stored in SQL Server is 26/3/2014 00:00:00.000. I need to cast CurDate to have all zeros in order to match database data



Solution 1:[1]

You can simply use

CurDate.Date and that will give you '26/3/2012 00:00:00'

Solution 2:[2]

Try to format DateTime:

DateTime dt = new DateTime(2014, 06, 21, 0, 0, 0);
Console.WriteLine(dt.ToString("dd.MM.yyyy HH:mm:ss tt"));

Result:

21.06.2014 00:00:00

More informations: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Solution 3:[3]

You could try this one:

// Parse the string you have, to create a datetime.
DateTime CurDate = DateTime.ParseExact('26/3/2014 12:00:00 AM', 
                                       "dd-MM-yyyy HH:mm:ss", 
                                        CultureInfo.InvariantCulture);

// Create the datetime you want based on the CurDate
DateTime result = new DateTime(CurDate.Year, CurDate.Month, CurDate.Day, 0, 0, 0);

For more information about ParseExact please have a look here.

Solution 4:[4]

Nowhere, in SQL Server or in .NET dates hasn't any presentation. They are just an numeric value. Don't care about that, both the SQL Server and .NET so smart that can pass parameters without any confusion. Just pass parameters of the correct data type.

Solution 5:[5]

Use 24 Hour Format

DateTime CurDate = DateTime.Parse("3/26/2014 12:00:00 AM");
Console.WriteLine("12 Hour Format: " + CurDate.ToString("dd-MM-yyyy hh:mm:ss"));
Console.WriteLine("24 Hour Format: " + CurDate.ToString("dd-MM-yyyy HH:mm:ss")); 

Solution 6:[6]

I know it's late but I think this was the proper answer for future references:

Console.WriteLine("Current Date with 0s on time part: " + DateTime.Now.ToString("yyyy-MM-dd 00:00:00.000"));

Solution 7:[7]

        this.dtGelisSaati = DateTime.Now;

set curency time values

        this.dtGelisSaati = DateTime.Today;

this ok. zero time values set.

Solution 8:[8]

Put .Date and get the date part with zero time part. I use Linq as:

var list = Results.Where(x => x.ExpDate.Date >= From.Date && x.ExpDate.Date <= To.Date).ToList();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve
Solution 2 Orion
Solution 3 Christos
Solution 4 Hamlet Hakobyan
Solution 5 Faisal
Solution 6 Ph0b0x
Solution 7 Osman Hal
Solution 8 Md Shahriar