简体   繁体   English

如何从datetime对象获取短日期格式

[英]How to get short date format from the datetime object

I am capturing the time in the text box (by using AJAX calender extender) the time in the string is 12/10/2013 , but when I assign the string to a datetime object it is converted into 12/10/2013 12:00:00 AM . 我在文本框中捕获时间(通过使用AJAX日历扩展器)字符串中的时间是12/10/2013 ,但是当我将字符串分配给datetime对象时,它将被转换为12/10/2013 12:00:00 AM

I want to use the date to filter the records in the database using the query below. 我想使用日期来使用下面的查询过滤数据库中的记录。 Please help 请帮忙

string date1 = txtDate1.Text;

DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", 

 System.Globalization.CultureInfo.InvariantCulture);
 string strQuery = "SELECT Story.UserName,Story.StoryId,COUNT(Likes.StoryID) AS         NumberOfOrders 
 FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=" + date1 + "
 GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC ;";

It's generally not a good idea to pass dates as strings in your queries because you will most likely run into formatting issues - leave it up to the Framework you are using decide on what the best format is. 在您的查询中将日期作为字符串传递通常不是一个好主意,因为您很可能遇到格式问题 - 将其留给您正在使用的框架决定最佳格式是什么。

In your circumstances, you can do this by using SqlParameter s eg 在您的情况下,您可以通过使用SqlParameter来完成此操作

DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName, Story.StoryId, COUNT(Likes.StoryID) AS NumberOfOrders 
    FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=@dateTime
    GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC";

using (SqlConnection connection = new SqlConnection("..."))
{
    using (SqlCommand cmd = new SqlCommand(strQuery, connection))
    {
        cmd.Parameters.AddWithValue("@dateTime", date);
        connection.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        ...
    }
}

Another important reason to use parameters when writing raw SQL is to ensure your user input is correctly sanatized and safe to pass to the DB. 在编写原始SQL时使用参数的另一个重要原因是确保您的用户输入被正确地保护并且安全地传递给DB。 Failure to do this can leave you open to various exploitations such as SQL Injection . 如果不这样做,您可以开始使用SQL注入等各种开发。

Instead of DateTime object you can use Date object. 您可以使用Date对象代替DateTime对象。

DateTime is an integer interpreted to represent both parts of DateTime (ie: date and time). DateTime是一个解释为表示DateTime的两个部分的整数(即:日期和时间)。 You will always have both date and time in DateTime. 您将始终在DateTime中同时拥有日期和时间。

ex: 例如:

   DateTime.Now.ToString("MM/dd/yyyy");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM