将日期字符串转换为其他格式的日期字符串 [英] Convert Date String to another Date string with different format

查看:127
本文介绍了将日期字符串转换为其他格式的日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将格式为 yyyyMMdd 的字符串日期转换为格式为 MM/dd/yyyy 的日期字符串.哪个是最好的选择?

I need to convert an string date with format yyyyMMdd to a date string with format MM/dd/yyyy. Which is the best to do it?

我正在这样做:

DateTime.ParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy")

但是我不确定,我认为必须有更好的方法.你觉得呢?

But I'm not sure, i think there must be a better way. What do you think?

推荐答案

您在做什么很好.

可能您可以通过使用 DateTime来改进它.TryParseExact ,并在成功解析后,将 DateTime 对象格式化为其他格式.

Probably you can improve it by using DateTime.TryParseExact and on successful parsing, format the DateTime object in other format.

string dateString = "20130916";
DateTime parsedDateTime;
string formattedDate;
if(DateTime.TryParseExact(dateString, "yyyyMMdd", 
                    CultureInfo.InvariantCulture, 
                    DateTimeStyles.None, 
                    out parsedDateTime))
{
    formattedDate = parsedDateTime.ToString("MM/dd/yyyy");
}
else
{
       Console.WriteLine("Parsing failed");
}

这篇关于将日期字符串转换为其他格式的日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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