C# 将字符串转换为没有时间的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1937601/
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
convert string to date without time
提问by Ognjen
This line
这条线
System.DateTime.Parse("09/12/2009");
convert date (string) to 9/12/2009 12:00:00 AM. How can I get a date in the form 9/12/2009.
将日期(字符串)转换为 9/12/2009 12:00:00 AM。我如何获得 2009 年 9 月 12 日表格中的日期。
after explanations I do:
解释后我做:
DateTime dt = System.DateTime.Parse(Request.Form["datepicker"]);
dt.ToString("dd/mm/yyyy");
/* and this code have time, why???*/
采纳答案by Mark Byers
Your problem is not with the parsing but with the output. Look at how ToStringworks for DateTime, or use this example:
您的问题不在于解析,而在于输出。看看ToString如何为 DateTime 工作,或者使用这个例子:
using System;
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Parse("09/12/2009");
Console.WriteLine(dt.ToString("dd/MM/yyyy"));
}
}
Or to get something in your locale:
或者在您的语言环境中获取一些东西:
Console.WriteLine(dt.ToShortDateString());
Update: Your update to the question implies that you do not understand fully my answer yet, so I'll add a little more explanation. There is no Date in .NET - there is only DateTime. If you want to represent a date in .NET, you do so by storing the time midnight at the start of that day. The time must always be stored, even if you don't need it. You cannot remove it. The important point is that when you display this DateTime to a user, you only show them the Date part.
更新:你对问题的更新意味着你还没有完全理解我的回答,所以我会添加更多的解释。.NET 中没有 Date - 只有 DateTime。如果你想在 .NET 中表示一个日期,你可以通过存储当天开始的午夜时间来实现。时间必须始终存储,即使您不需要它。你不能删除它。重要的一点是,当您向用户显示此日期时间时,您只向他们显示日期部分。
回答by o.k.w
Anything parsed to a DateTime object will contain date+time. If no time is sepcified, the assumed value will be 0000hr.
任何解析为 DateTime 对象的内容都将包含日期+时间。如果没有指定时间,则假定值为 0000 小时。
To get the date-only representation, it's up to how you format it to string.
要获得仅日期表示,取决于您如何将其格式化为字符串。
E.g. theDate.ToString("dd/MM/yyyy")
例如 theDate.ToString("dd/MM/yyyy")
Refer to the MSDN Date and Time Format Strings.
请参阅 MSDN日期和时间格式字符串。
回答by Taja_100
if you want to convert gridview datetime column to date only column use this code :
如果要将 gridview 日期时间列转换为仅日期列,请使用以下代码:
raddgvDaybook.Rows.ToList().ForEach(x =>
{
DateTime dt = DateTime.Parse(x.Cells["Vocdate"].Value.ToString());
string str = string.Format("{0:MM/dd/yyyy}", dt);
x.Cells["Vocdate"].Value = str;
});
I tested the code it will work if you bind the datetime as string in dgv.
如果您将日期时间绑定为 dgv 中的字符串,我测试了它将起作用的代码。