C# Convert.ToDateTime:如何设置格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15203534/
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.ToDateTime: how to set format
提问by Refael
I use convert like:
我使用转换如:
Convert.ToDateTime(value)
but i need convert date to format like "mm/yy".
I'm looking for something like this:
但我需要将日期转换为“mm/yy”等格式。
我正在寻找这样的东西:
var format = "mm/yy";
Convert.ToDateTime(value, format)
采纳答案by Fredrik M?rk
You should probably use either DateTime.ParseExact
or DateTime.TryParseExact
instead. They allow you to specify specific formats. I personally prefer the Try
-versions since I think they produce nicer code for the error cases.
您可能应该使用其中之一DateTime.ParseExact
或DateTime.TryParseExact
代替。它们允许您指定特定格式。我个人更喜欢Try
-versions,因为我认为它们为错误情况生成更好的代码。
回答by MarcinJuraszek
If value
is a string
in that format and you'd like to convert it into a DateTime
object, you can use DateTime.ParseExact
static method:
如果value
是string
那种格式并且您想将其转换为DateTime
对象,则可以使用DateTime.ParseExact
静态方法:
DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);
Example:
例子:
string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
Console.WriteLine(myDate.ToShortDateString());
Result:
结果:
2012-12-01
回答by D Stanley
DateTime
doesn't have a format. the format only applies when you're turning a DateTime
into a string, which happens implicitly you show the value on a form, web page, etc.
DateTime
没有格式。该格式仅在您将 aDateTime
转换为字符串时才适用,这种情况隐含地发生在您在表单、网页等上显示该值时。
Look at whereyou're displaying the DateTime and set the format there (or amend your question if you need additional guidance).
查看您显示 DateTime 的位置并在那里设置格式(或者如果您需要其他指导,请修改您的问题)。
回答by jomsk1e
回答by Michael Freidgeim
You can use Convert.ToDateTime is it is shown at How to convert a Datetime string to a current culture datetime string
您可以使用 Convert.ToDateTime 是否显示在如何将日期时间字符串转换为当前区域性日期时间字符串
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
var result = Convert.ToDateTime("12/01/2011", usDtfi)
回答by pravin...
You can use this also.
你也可以使用这个。
dtFromDate = Convert.ToDateTime(DateTime.ParseExact(fromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture));