首页 > 其他 > 详细

[翻译]Convert a date to the RFC822 standard for use in RSS feeds(在RSS源中间日期转换成RFC822标准使用)

时间:2020-01-17 13:46:26      阅读:79      评论:0      收藏:0      [点我收藏+]

转载自:https://madskristensen.net/blog/convert-a-date-to-the-rfc822-standard-for-use-in-rss-feeds/

RFC822标准日期时间格式如下

Wed, 27 Sep 2006 21:36:45 +0200

 

而我们在C#中运行以下代码

DateTime.Now.ToString("r")

得到的日期时间如下:

Wed, 27 Sep 2006 21:49:19 GMT

GMT(格林尼治标准时间)是RFC822的可接受值,当在我这个地方不适用,他应该是+0200。在我所试的所

有电脑上都失败了。即便我尝试手动编写这样的格式串,他仍旧是不起作用的。

DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzzz")

输出

Wed, 27 Sep 2006 21:36:45 +02:00

 

以上输出几乎接近正确的格式了,但是时区格式还不正确。经过网上搜索以后,问题逐渐明朗:显然.NET不允许你使用DateTime

的标准格式转换到RFC822标准。因而我不得不写一个方法来完成这个转换。

 

/// <summary>

/// Converts a regular DateTime to a RFC822 date string.

/// </summary>

/// <returns>The specified date formatted as a RFC822 date string.</returns>

private static string GetRFC822Date(DateTime date)

{

  int offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;

  string timeZone = "+" + offset.ToString().PadLeft(2, 0);

 

  if (offset < 0)

  {

    int i = offset * -1;

    timeZone = "-" + i.ToString().PadLeft(2, 0);

  }

 

  return date.ToString("ddd, dd MMM yyyy HH:mm:ss " + timeZone.PadRight(5, 0));

}

只需传入一个DateTime实例,他将返回一个格式正确的RFC822字符串,并且可以通过验证。

转载自:https://madskristensen.net/blog/convert-a-date-to-the-rfc822-standard-for-use-in-rss-feeds/

[翻译]Convert a date to the RFC822 standard for use in RSS feeds(在RSS源中间日期转换成RFC822标准使用)

原文:https://www.cnblogs.com/passedbylove/p/12205325.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!