简体   繁体   English

陷入C#DateTime ToString()格式问题

[英]Stumped on C# DateTime ToString() formatting problem

I am getting some junk data returned from a ToString() call on a DateTime object in C# and I'm afraid I'm stumped after poking around with it for a while. 我在C#中的DateTime对象上从ToString()调用返回了一些垃圾数据,恐怕我闲逛了一会后才感到困惑。

The function is supposed to format dates to be compliant with RFC 822 (as required by the RSS spec) and looks like: 该功能应该格式化日期以符合RFC 822(RSS规范要求),并且看起来像:

public static string FormatPubDate(DateTime pubDate) 
{
    string _rfc822Format = "ddd, dd MMM yyyy HH:mm:ss";
    string _tmp = pubDate.ToUniversalTime().ToString(_rfc822Format);

    return pubDate.ToString(_tmp + " UT");
}

Which should be what I want, from what I can read of the DateTime ToString() docs. 从我能读到的DateTime ToString()文档中,应该是我想要的。

However, for some dates it's generating junk: 但是,对于某些日期,它会产生垃圾:

 Console.WriteLine(FormatPubDate(new DateTime(2008, 12, 16, 13, 44, 33)));
 Console.WriteLine(FormatPubDate(new DateTime(2008, 12, 17, 13, 44, 33)));
 Console.WriteLine(FormatPubDate(new DateTime(2009, 3, 18, 4, 17, 20)));
 Console.WriteLine(FormatPubDate(new DateTime(2009, 4, 30, 10, 44, 33)));

Yields: 产量:

Tue, 16 Dec 2008 19:44:33 UT
We17, 17 Dec 2008 19:44:33 UT
We18, 18 3ar 2009 09:17:20 UT
T10u, 30 Apr 2009 15:44:33 UT

Any ideas why it's returning We18 instead of Wed and 3ar instead of Mar? 有什么想法为什么要返回We18而不是Wed和3ar而不是Mar?

You're problem is the last 你的问题是最后

return pubDate.ToString(_tmp + " UT");

You're doing a second ToString() on the DateTime with the formatted value, as the formatter... 您正在使用格式化后的值在DateTime上执行第二次ToString(),作为格式化程序...

Try changing it to 尝试将其更改为

string _rfc822Format = "ddd, dd MMM yyyy HH:mm:ss";
string _tmp = pubDate.ToUniversalTime().ToString(_rfc822Format);

return _tmp + " UT";

您可以改用它吗?:

String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123

You are currently calling ToString on the date, passing in your RFC format, then you are calling ToString on the date again, apssing in your already converted date + "UT" as the format, I'm suprised you get anything good coming out! 您当前正在日期上调用ToString,以RFC格式传递,然后再次在日期上调用ToString,以您已经转换的日期+“ UT”作为格式,我很高兴您能收到任何好的结果!

Try this: 尝试这个:

public static string FormatPubDate(DateTime pubDate) 
{
    string _rfc822Format = "ddd, dd MMM yyyy HH:mm:ss";
    return pubDate.ToUniversalTime().ToString(_rfc822Format) + " UT";

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM