C# 将 YYYYMMDD 字符串转换为 MM/DD/YYYY 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11848122/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:29:40  来源:igfitidea点击:

Convert YYYYMMDD string to MM/DD/YYYY string

c#datetime

提问by JTRookie86

I have a date that is stored as a string in the format YYYYDDMM. I would like to display that value in a 'MM/DD/YYYY' format. I am programming in c#. The current code that I am using is as follows:

我有一个以 YYYYDDMM 格式存储为字符串的日期。我想以“MM/DD/YYYY”格式显示该值。我正在用 C# 编程。我正在使用的当前代码如下:

txtOC31.Text = dr["OC31"].ToString().Trim();
strOC31date = dr["OC31DATE"].ToString().Trim();
DateTime date31 = DateTime.Parse(strOC31date);
strOC31date = String.Format("{0:MM/dd/yyyy}", date31);

However, I am getting an error because the YYYYMMDD string (strOC31date) is not being recognized as a valid datetime.

但是,我收到一个错误,因为 YYYYMMDD 字符串 (strOC31date) 未被识别为有效的日期时间。

采纳答案by Steve

DateTime.ParseExact with an example

DateTime.ParseExact 示例

string res = "20120708";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));

回答by Leon

Instead of DateTime.Parse(strOC31date);use DateTime.ParseExact()method, which takes format as one of the parameters.

而不是DateTime.Parse(strOC31date);使用DateTime.ParseExact()方法,它将格式作为参数之一。

回答by James Michael Hare

Use ParseExact()(MSDN) when the string you are trying to parse is not in one of the standard formats. This will allow you to parse a custom format and will be slightly more efficient (I compare them in a blog post here).

当您尝试解析的字符串不是标准格式之一时,请使用ParseExact()( MSDN)。这将允许您解析自定义格式,并且效率会稍微提高一些(我在此处的博客文章中对它们进行了比较)。

DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", null);

Passing nullfor the format provider will default to DateTimeFormatInfo.CurrentInfoand is safe, but you probably want the invariant culture instead:

传递null给格式提供程序将默认为DateTimeFormatInfo.CurrentInfo并且是安全的,但您可能需要不变的文化:

DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyMMdd", DateTimeFormatInfo.InvariantInfo);

Then your code will work.

然后您的代码将起作用。

回答by Chris

You want the method DateTime.ParseExact.

您需要DateTime.ParseExact方法。

DateTime date31 = DateTime.ParseExact(strOC31date, "yyyyddMM", CultureInfo.InvariantCulture);