gpt4 book ai didi

c# - 难倒在 C# DateTime ToString() 格式化问题

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:54 24 4
gpt4 key购买 nike

我从 C# 中的 DateTime 对象上的 ToString() 调用返回了一些垃圾数据,我担心在研究它一段时间后我被难住了。

该函数应该格式化日期以符合 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");
}

根据我对 DateTime ToString() 文档的了解,这应该是我想要的。

但是,对于某些日期,它会产生垃圾:

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

产量:

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 而不是 Wed 和 3ar 而不是 Mar 吗?

最佳答案

你的问题是最后一个

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

您正在 DateTime 上使用格式化值执行第二个 ToString(),作为格式化程序...

尝试将其更改为

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

return _tmp + " UT";

关于c# - 难倒在 C# DateTime ToString() 格式化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/807690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com