日期:2014-05-17  浏览次数:21000 次

关于DateTime.toString(string)返回字符串中加入反斜杠的问题
我们都知道在DateTime.toString(string)方法中,输入参数是日期的自定义格式,关于自定义格式按照MSDN上的解释:
\c
表示转义符并将字符“c”显示为文本(当该字符前带有转义符 (\) 时)。若要将反斜杠字符本身插入结果字符串,应用程序应使用两个转义符(“\\”)。

所以我写了一下的C#代码,作用是利用时间来产生一个特定格式的路径,比如2013-03-22 09:00:00的时间就可以生成路径:2013年\03月\22日\的路径,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Globalization;

namespace DateTimeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string strDateTime = "130322090000";

            DateTime dtDateTime = DateTime.ParseExact(strDateTime, "yyMMddHHmmss", CultureInfo.InvariantCulture);

            string s = dtDateTime.ToString("yyyy年\\MM月\\dd日\\");

            Console.WriteLine(s);
            Console.Read();
        }
    }
}

 代码运行的时候发生异常,提示字符串格式不正确,可我对照MSDN上的说明仔细的检查,实在看不出有什么不对的地方,还望朋友们帮我解决一下,十分感谢
c# DateTime.toString() 自定义格式

------解决方案--------------------
 string s = dtDateTime.ToString("yyyy年\\\\MM月\\\\dd日");

这个样子就可以了
------解决方案--------------------
string strDateTime = "130322090000";

            DateTime dtDateTime = DateTime.ParseExact(strDateTime, "yyMMddHHmmss", CultureInfo.InvariantCulture);

            string s = dtDateTime.ToString(@"yyyy年\\MM月\\dd日");
            Console.WriteLine(s);
            Console.Read();