从 C# 中的日期时间中删除时间并保留日期时间格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16326709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
removing time from datetime in c# and retaining datetime format
提问by blue piranha
How can I remove time from datetime and store the output in datetime format? I do not want to show the time.
如何从日期时间中删除时间并以日期时间格式存储输出?我不想显示时间。
Say I have
说我有
string d = "2/27/2013 4:18:53 PM"
How can I store the output in a DateTime variable with only the date and not time.
如何将输出存储在只有日期而不是时间的 DateTime 变量中。
I can use ToShortDateString() but then it return a string and not datetime.
我可以使用 ToShortDateString() 但它返回一个字符串而不是日期时间。
My ultimate goal is to sort the date column chronologically which can only be done if all the entries are in datetime format and not string.
我的最终目标是按时间顺序对日期列进行排序,这只有在所有条目都是日期时间格式而不是字符串时才能完成。
采纳答案by C???
The Dateproperty of the DateTimestruct will give you a date but it will always have a time component that represents midnight ("00:00:00"). If you're starting with a string, you might be able to work with something like this:
结构体的Date属性DateTime会给你一个日期,但它总是有一个代表午夜(“00:00:00”)的时间组件。如果你从一个字符串开始,你可能可以使用这样的东西:
DateTime d = DateTime.Parse("2/27/2013 4:18:53 PM").Date; // 2/27/2013 12:00:00 AM
Just make sure you perform your comparison on DateTimeobjects (i.e. omit all usages of ToString()).
只要确保您对DateTime对象进行比较(即省略 的所有用法ToString())。
Alternatively, you can format your date in the "sortable" time format:
或者,您可以以“可排序”时间格式格式化您的日期:
string d = DateTime.Parse("2/27/2013 4:18:53 PM").ToString("s");
or
或者
string d = yourDateTime.ToString("s");
For the above case dwould be 2013-02-27T16:18:53. When sorted alphabetically, the strings will be in chronological order.
对于上述情况d将是2013-02-27T16:18:53。按字母顺序排序时,字符串将按时间顺序排列。
回答by C???
As easy as this:
就这么简单:
d.ToString("mm/dd/yyyy");
DateTime date = DateTime.Parse(d);
回答by Varun Tej Reddy
DateTime dt = DateTime.now(); (To get Any Date)
string datewithMonth= dt.ToString("MMMM dd, yyyy");
string onlyDate = DateTime.Parse(datewithMonth).ToShortDateString();
Here we get result as 1/1/2014. So that we can perform select operation on sql like this:
在这里我们得到结果为1/1/2014。这样我们就可以像这样对 sql 执行选择操作:
searchQuery = "select * from YourTableName where ColumnName = ' " + onlyDate + " ' ";
回答by Craig
What about removing the time in culture:-
去除文化中的时间怎么样:-
var submissionDateData = DateTime.Now.ToShortDateString();
var submissionDate = DateTime.Parse(submissionDateData, CultureInfo.CreateSpecificCulture("en-GB"));
First line gives 02/11/2015
第一行给出 02/11/2015
Second line gives 11/02/2015 12:00:00 AM
第二行给出 11/02/2015 12:00:00 AM
Do you have to do a string split on this or is there a way to get rid of the time?
您是否必须对此进行字符串拆分,或者有没有办法摆脱时间?

