将20121004(yyyyMMdd)转换为有效日期时间? [英] Convert 20121004 (yyyyMMdd) to a valid date time?

查看:59
本文介绍了将20121004(yyyyMMdd)转换为有效日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下格式的字符串 yyyyMMdd ,我正在尝试使其看起来像这样:

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

yyyy-MM-dd

当我尝试时:

string date = "20121004";

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

我得到了错误:

FormatException:无法将字符串识别为有效的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";
     }
}

推荐答案

只需使用 DateTime.ParseExact 方法:

string date = "20121004";

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

这还提供了在使用连字符重新格式化日期之前验证日期的优点.如果日期不在有效范围内,或者格式不匹配,则 ParseExact 引发您可以捕获的异常.

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

这篇关于将20121004(yyyyMMdd)转换为有效日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆