C# 将 20121004 (yyyyMMdd) 转换为有效的日期时间?

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

Convert 20121004 (yyyyMMdd) to a valid date time?

c#

提问by Xaisoft

I have a string in the following format yyyyMMddand I am trying to get it to look like this:

我有一个以下格式的字符串,yyyyMMdd我试图让它看起来像这样:

yyyy-MM-dd

yyyy-MM-dd

When I try:

当我尝试:

string date = "20121004";

Convert.ToDateTime(date).ToString("yyyy-MM-dd");

I get the error:

我收到错误:

FormatException: String was not recognized as a valid DateTime.

FormatException: String was not recognized as a valid DateTime.

Would the following work or would I run into a problem:

以下是否有效,或者我会遇到问题:

private string GetValidDate(string date,string format)
{
    DateTime result;
    if(DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    {
        return date;
    }
    else if(DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    { 
        return DateTime.ParseExact(date, "yyyyMMdd",
                CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
     }
     else
     {
        return "Invalid Date Format";
     }
}

采纳答案by Philip Daubmeier

Just use the DateTime.ParseExactmethod:

只需使用以下DateTime.ParseExact方法:

string date = "20121004";

string result = DateTime.ParseExact(date, "yyyyMMdd",
                CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

This also provides the advantage of validating the date before reformatting it with the hyphens. ParseExactthrows an exception you can catch, if the date is not in valid range, or the format does not match.

这也提供了在使用连字符重新格式化日期之前验证日期的优势。ParseExact如果日期不在有效范围内或格式不匹配,则抛出一个您可以捕获的异常。

回答by Tim Sullivan

Here is an extension method I use.

这是我使用的扩展方法。

/// <summary>
/// Converts a string to a dateTime with the given format and kind.
/// </summary>
/// <param name="dateTimeString">The date time string.</param>
/// <param name="dateTimeFormat">The date time format.</param>
/// <param name="dateTimeKind">Kind of the date time.</param>
/// <returns></returns>
public static DateTime ToDateTime(this string dateTimeString, string dateTimeFormat, DateTimeKind dateTimeKind)
{
    if (string.IsNullOrEmpty(dateTimeString))
    {
        return DateTime.MinValue;
    }

    DateTime dateTime;
    try
    {
        dateTime = DateTime.SpecifyKind(DateTime.ParseExact(dateTimeString, dateTimeFormat, CultureInfo.InvariantCulture), dateTimeKind);
    }
    catch (FormatException)
    {
        dateTime = DateTime.MinValue;
    }

    return dateTime;
}

回答by James Cronen

It's a little ugly, but how about this?

有点难看,不过这个怎么样?

date.Insert(6, "-").Insert(4, "-");

If you can assume you're coming in with a string representing a valid date and you don't need to do any other date-ish logic, then why go to a DateTimein the first place?

如果您可以假设您输入的是一个表示有效日期的字符串,并且您不需要执行任何其他日期逻辑,那么为什么DateTime首先要转到 a呢?

回答by Security Hound

I get the error:

FormatException: String was not recognized as a valid DateTime.

我收到错误:

FormatException: String 未被识别为有效的 DateTime。

You are getting this error because you are not telling the ToDateTime() method how to figure out to parse your string.

您收到此错误是因为您没有告诉 ToDateTime() 方法如何解析您的字符串。

If you use the following method:

如果您使用以下方法:

public static DateTime ParseExact(
    string s,
    string format,
    IFormatProvider provider,
    DateTimeStyles style
)

You won't get this error. After you generate a DateTime variable just display it in the format yyyy-dd-mmusing the ToString() method.

你不会得到这个错误。生成 DateTime 变量后,只需yyyy-dd-mm使用 ToString() 方法以格式显示它。

public string ToString(
    string format,
    IFormatProvider provider
)

http://msdn.microsoft.com/en-us/library/8tfzyc64
http://msdn.microsoft.com/en-us/library/9h21f14e

I know this basically repeats the same information as everyone else but it also provides him the ability to understand what the two methods he needs to use actually does.

http://msdn.microsoft.com/en-us/library/8tfzyc64
http://msdn.microsoft.com/en-us/library/9h21f14e

我知道这基本上重复了与其他人相同的信息,但它也为他提供了能够理解他需要使用的两种方法实际上做了什么。