在JavaScript中将Json时间戳转换为常规日期和时间

17

我有一个Json时间戳,希望使用Javascript将其转换为简单的日期时间格式。

我需要以下格式的日期和时间: dd-mm-yyyy hr:mn

这是一个示例Json日期,我想从中提取时间戳: "timestamp": 1326439500

{
   "count": 2,
   "d": [
      {
         "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
         "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
         "link": "http://wik.io/info/US/309201303",
         "timestamp": 1326439500,
         "image": null,
         "embed": null,
         "language": null,
         "user": null,
         "user_image": null,
         "user_link": null,
         "user_id": null,
         "geo": null,
         "source": "wikio",
         "favicon": "http://wikio.com/favicon.ico",
         "type": "blogs",
         "domain": "wik.io",
         "id": "2388575404943858468"
      },
      {
         "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
         "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
         "link": "http://wik.io/info/US/309198933",
         "timestamp": 1326439320,
         "image": null,
         "embed": null,
         "language": null,
         "user": null,
         "user_image": null,
         "user_link": null,
         "user_id": null,
         "geo": null,
         "source": "wikio",
         "favicon": "http://wikio.com/favicon.ico",
         "type": "blogs",
         "domain": "wik.io",
         "id": "16209851193593872066"
      }
   ]
} 

1
var date = new Date(timestamp); var hours = date.getHours(); // 时间戳中的分钟部分 var minutes = date.getMinutes(); // 时间戳中的秒钟部分 var seconds = date.getSeconds();// 将时间以 10:30:23 的格式显示 var formattedTime = hours + ':' + minutes + ':' + seconds; - Rajat Singhal
@RajatSinghal那只会输出时间,不是吗? - praneybehl
你可以从日期对象中获取日期、年份等信息...而不是使用getHours,可以使用getYear... - Rajat Singhal
1
JSON没有时间戳。它没有日期/时间的概念 - 它只是一个传输封装。那个数字是生成JSON文本的任何语言的时间戳。 - Marc B
3个回答

22
日期以自纪元以来的毫秒数返回。以下代码创建JS日期对象:
var d = new Date(1245398693390);
var formattedDate = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();
var hours = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
var minutes = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
var formattedTime = hours + ":" + minutes;

formattedDate = formattedDate + " " + formattedTime;

这里有一个可用的代码片段:链接
编辑1:自从此答案发布以来,很多事情发生了变化(尽管原始答案仍然有效)。在ES6引入const / let和模板文字之后,稍微更简洁的方法是:
const d = new Date(1245398693390);
let formattedDate = `${d.getDate()}-${d.getMonth()}-${d.getFullYear()}`;
const hours = d.getHours().toString().padStart(2, 0);
const minutes = d.getMinutes().toString().padStart(2, 0);
const formattedTime = `${hours}:${minutes}`;

formattedDate = `${formattedDate} ${formattedTime}`;

这里有一个可以工作的代码示例:示例链接

你还可以通过使代码略微不易读来使其更加简洁:

function getFormattedDate()  {
    const padWithZero = (num, targetLength) => String(num).padStart(targetLength, '0');
    const d = new Date(1245398693390);
    return `${d.getDate()}-${d.getMonth()}-${d.getFullYear()} ${padWithZero(d.getHours(), 2)} ${padWithZero(d.getMinutes(), 2)}`;
}

这里有一个可用的示例:工作的代码

也可以使用 .toLocaleString() 并从中选择所需的元素进行操作。


谢谢你的快速示例,但是它给了我这个完整的时间日期: 2009-06-19T08:04:53.390Z而我想要类似于 dd-mm-yyyy hr:mn 的格式。 - praneybehl
@praneybehl,我误解了。你只是想要时间吗? - James Hill
@praneybehl,我认为你应该将这些信息添加到你的原始问题中——它没有提到日期格式化。 - James Hill
@praneybehl,没有人感到不满。我将你的问题投票下降是因为你在回答评论中开始添加额外的信息,从而显示出你的问题是不充分的。由于你添加了额外的信息,所以我投票支持你:) - James Hill
@JamesHill 感谢您的出色回答。 - Luffy
显示剩余4条评论

6

Date的原型扩展,添加一个格式化函数,例如:

Date.prototype.format = function (formatString) {
    // Returns a formatted date string
    var month = this.getMonth() + 1,
        day = this.getDate(),
        year = this.getFullYear(),
        hours24 = this.getHours(),
        hours = (hours24 === 0 ? 12 : hours24 > 12 ? hours24 - 12 : hours24),
        meridiem = hours24 >= 12 ? "PM" : "AM",
        minutes = this.getMinutes(),
        seconds = this.getSeconds();

    return formatString.replace(/(MM)/g, month.padLeft(2, '0'))
        .replace(/(M)/g, month)
        .replace(/(dd)/g, day.padLeft(2, '0'))
        .replace(/(d)/g, day)
        .replace(/(yyyy)/ig, year)
        .replace(/(yy)/ig, year.toString().substring(2, 4))
        .replace(/(hh)/g, hours.padLeft(2, '0'))
        .replace(/(h)/g, hours)
        .replace(/(HH)/g, hours24.padLeft(2, '0'))
        .replace(/(H)/g, hours24)
        .replace(/(mm)/g, minutes.padLeft(2, '0'))
        .replace(/(m)/g, minutes)
        .replace(/(ss)/g, seconds.padLeft(2, '0'))
        .replace(/(s)/g, seconds)
        .replace(/(tt)/g, meridiem.toLowerCase())
        .replace(/(TT)/g, meridiem);
};

然后,要将时间戳转换为所需的格式 dd-mm-yyyy hr:mn(根据您的评论提到),请按以下步骤操作:
var dateString = new Date(timestamp).format("dd-MM-yyyy hh:mm");

[编辑] 这是相应的填充函数:

Number.prototype.padLeft = function (width, padChar) {
    // Returns a padded string
    padChar = padChar || ' ';
    var value = this.toString();
    while (value.length < width) {
        value = padChar + value;
    }
    return value;
};

1
哇,非常全面。感谢你花时间解释这个问题。由于有人将我的问题标记为下降,我现在无法投票,否则我会投票支持你的回答。再次感谢。 - praneybehl

2
<script>
var timestamp=1326439320;
var date=new Date(timestamp);
var hours = date.getHours(); // minutes part from the timestamp
var minutes = date.getMinutes(); // seconds part from the timestamp
var seconds = date.getSeconds(); // will display time in 10:30:23 format
 var formattedTime = hours + ':' + minutes + ':' + seconds;
alert(formattedTime);
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接