string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);
//////// this methods convert string value to datetime
///////// in order to print date
Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);
16
如果您不确定输入值,也可以使用DateTime.TryParseExact(),如下所示 .
DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
return outputDateTimeValue;
}
else
{
// Handle the fact that parse did not succeed
}
12 回答
由于您正在处理基于24小时的时间,并且您使用逗号分隔秒分数,我建议您指定自定义格式:
你基本上有两种选择 .
DateTime.Parse()
和DateTime.ParseExact()
.第一个是非常宽容的语法,并将以许多不同的格式解析日期 . 对于可能以不同格式出现的用户输入是有益的 .
ParseExact将允许您指定用于解析的日期字符串的确切格式 . 如果您的字符串始终采用相同的格式,则最好使用此方法 . 这样,您可以轻松检测到与预期数据的任何偏差 .
您可以解析用户输入,如下所示:
如果您有特定的字符串格式,则应使用其他方法:
"d"
代表短日期模式(请参阅MSDN for more info),null
指定应使用当前区域性来解析字符串 .试试这个
更好的方法是:
似乎没有人实现扩展方法 . 在@CMS's answer的帮助下:
工作和改进的完整源代码示例如下:Gist Link
试试下面的内容,其中strDate是您的'MM / dd / yyyy'格式的日期
Convert.ToDateTime或DateTime.Parse
使用DateTime.Parse(string)
如果您不确定输入值,也可以使用DateTime.TryParseExact(),如下所示 .
我试过各种方法 . 对我有用的是:
data
对我来说就是这样的时间9/24/2017 9:31:34 AM世界上不同的文化以不同的方式写日期字符串 . 例如,在美国01/20/2008是2008年1月20日 . 在法国,这将抛出InvalidFormatException . 这是因为法国将日期时间视为日/月/年,而在美国则是月/日/年 .
因此,像2008年1月20日这样的字符串将在2008年1月20日在法国解析,然后在美国抛出InvalidFormatException .
要确定当前的区域性设置,可以使用System.Globalization.CultureInfo.CurrentCulture .
Put this code in a static class
> public static class ClassName{ }
In this way, you can use