简单的日期时间格式为YYYYMMDD

4
我在时间格式方面遇到了一些小问题。 我希望能够将日期时间数据输入转换为YYYY-MM-DD的输出形式,例如将输入19901209转换为1990-12-09
此外,我还想知道是否有其他方法以不同的格式获取数据,例如将指定格式的数据 19901209 转换为DD-MM-YYYYMM-DD-YYYY
非常感谢您的帮助。
4个回答

10
DateTime.ParseExact("19901209", "yyyyMMdd",null).ToString("yyyy-MM-dd")

4

使用DateTime.ParseExact方法,您可以使用特定格式解析日期:

var date = DateTime.ParseExact("19901209", "yyyyMMdd", CultureInfo.InvariantCulture);

然后,您可以使用DateTime.ToString(string)方法和格式字符串以任何您喜欢的方式对其进行格式化:

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

3
        string sDate = "19901209";
        string format = "yyyyMMdd";

        System.Globalization.CultureInfo provider = 
                             System.Globalization.CultureInfo.InvariantCulture;
        DateTime result = DateTime.ParseExact(sDate, format, provider); 
        // result holds wanted DateTime

0

作为另一种选择。 您可以使用SubString()方法将字符串“19901209”分成三个单独的字符串,例如sYear="1990"sMonth="12"sDate="09"。 然后将这些字符串连接成一个字符串,例如sNewDate = sYear+"-"+sMonth+"-"+sDate,然后在一个DateTime变量dtDate中,按您需要的格式格式化字符串,例如DateTime dtDate = Convvert.ToDateTime(sNewDate.ToString("Your Desired Format"));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接