本文介绍了难倒C#的DateTime的ToString()格式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一些垃圾数据从一个toString()调用在C#中返回的DateTime对象上我怕我与它打交道了一段时间后难住了。

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.

该功能应该格式的日期是符合RFC 822(根据需要由RSS规范),看起来像:

The function is supposed to format dates to be compliant with RFC 822 (as required by the RSS spec) and looks like:

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");
}



这应该是我想要的东西,从我所读的DateTime的ToString

Which should be what I want, from what I can read of the DateTime ToString() docs.

However, for some dates it's generating junk:

然而,对于一些日期它产生的垃圾C> Console.WriteLine(FormatPubDate(新的DateTime(2008,12,16,13,44,33)));
Console.WriteLine(FormatPubDate(新日期时间(2008年,12,17,13,44,33)));
Console.WriteLine(FormatPubDate(新日期时间(2009年,3,18,4,17,20)));
Console.WriteLine(FormatPubDate(新日期时间(2009,4,30,10,44,33)));

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

任何想法,为什么它返回WE18而不是周三和3AR,而不是Mar吗?

Any ideas why it's returning We18 instead of Wed and 3ar instead of Mar?

推荐答案

你的问题是最后一个

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

您正在做第二的ToString()上日期时间的格式化的值,如格式化。 ..

You're doing a second ToString() on the DateTime with the formatted value, as the formatter...

尝试将其更改为

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

return _tmp + " UT";

这篇关于难倒C#的DateTime的ToString()格式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:35