如何使用JavaScript格式化Twitter / Facebook提要日期 [英] How to format Twitter/Facebook feed date with JavaScript

查看:101
本文介绍了如何使用JavaScript格式化Twitter / Facebook提要日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找这个确切问题的答案:如何仅在JS中使用Objective-C格式化Facebook / Twitter日期(从JSON提要)

I'm looking for an answer to this exact question: How to format Facebook/Twitter dates (from the JSON feed) in Objective-C only in JS.

从Twitter返回的日期如下:Wed Oct 17 21:22:27 +0000 2012
还有FB它看起来像这样:2012-10-18T11:21:30 + 0000

The date returned from Twitter looks like this: Wed Oct 17 21:22:27 +0000 2012 And from FB it looks like this: 2012-10-18T11:21:30+0000

我觉得很奇怪(而且很烦人),他们没有unix时间戳,有人看到了这个原因吗?

I find it very strange (and highly annoying) that they don't include a unix timestamp, anyone see a reason for this?

推荐答案

日期字符串解析是一个非常常见的问题,对此肯定已经有答案了。无论如何...

Date string parsing is a very frequently asked question, there are surely answers already for this. Anyhow...

如果日期格式为2012-10-18T11:21:30 + 0000(几乎等于ISO8601),且偏移量始终为+0000(您可以使用以下方法创建合适的日期对象:

If the date format is 2012-10-18T11:21:30+0000 (which is pretty much ISO8601) and the offset is always +0000 (i.e. UTC), you can create a suitable date object using:

function isoStringToDate(s) {
  var b = s.split(/[-t:+]/ig);
  return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5]));
}

,它将返回为该UTC时间设置的本地日期对象。请注意,这取决于将用户系统设置为适当的时区。

which will return a local date object set for that UTC time. Note that this depends on the user's system being set to an appropriate timezone.

可以转换Facebook格式(2012年10月17日星期三21:22:27 +0000)类似地:

The Facebook format (Wed Oct 17 21:22:27 +0000 2012) format can be converted similarly:

function fbStringToDate(s) {
  var b = s.split(/[: ]/g);
  var m = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5, jul:6,
           aug:7, sep:8, oct:9, nov:10, dec:11};

  return new Date(Date.UTC(b[7], m[b[1].toLowerCase()], b[2], b[3], b[4], b[5]));
}

再次假设偏移量始终为+0000(UTC)。如果需要其他偏移量,可以在返回之前将其应用于创建的日期对象。

Again assuming that the offset it always +0000 (UTC). If there is a need for some other offset, it can be applied to the created date object before returning it.

这篇关于如何使用JavaScript格式化Twitter / Facebook提要日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆