Question

I'm trying to save a date in database with ASP.NET. The datatype of Date in the database is datetime. I want to save it as for example (23/02/2014 00:00:00)

That is, I want to save Date, Month and Year, and then have time always be 00:00:00. I also want to have zeros before month and/or day when they are only one number. e.g. 02/06/2014 instead of 2/6/2014.

This is possible when the datatype is varchar but how would I do this when the datatype is datetime?

Was it helpful?

Solution

dateTime.ToString("dd/MM/yyyy");

will set the time to zero. MM and dd will add zero if needed

SQL will know the correct date if you add this:

DateTime.Now.ToString("dd/MM/yyyy",System.Globalization.CultureInfo.GetCultureInfo("he-IL"));

update

System.Globalization.CultureInfo info = CultureInfo.CurrentCulture;
          Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("he-IL");

            command.Parameters.AddWithValue("@info",DateTime.Now);
          Thread.CurrentThread.CurrentCulture = info;

OTHER TIPS

You should store the DataTime on the database without problem using Parameter for sample:

command.Parameters.Add("DateField", SqlDbType.DateTime, datetime);

When you want to show on asp.net page, you should get the DateTime struct and format it , for sample:

label1.Text = dateTime.ToString("MM/dd/yyyy");

To know more about dateTime formats, look this link on MSDN documentation: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Just use a date type parameter and the Date property.

command.Parameters.AddWithValue("@info", DateTime.Now.Date);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top