DateTime Asp.NET

ε祈祈猫儿з 提交于 2019-12-11 08:22:26

问题


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?


回答1:


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;



回答2:


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




回答3:


Just use a date type parameter and the Date property.

command.Parameters.AddWithValue("@info", DateTime.Now.Date);


来源:https://stackoverflow.com/questions/21969649/datetime-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!