从unix时间戳到datetime [英] from unix timestamp to datetime

查看:201
本文介绍了从unix时间戳到datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类似 / Date(1370001284000 + 0200)/ 作为时间戳。我猜这是一个unix日期,不是吗?如何将其转换为如下日期: 31.05.2013 13:54:44

I have something like /Date(1370001284000+0200)/ as timestamp. I guess it is a unix date, isn't it? How can I convert this to a date like this: 31.05.2013 13:54:44

我尝试过<一个用于1370001284的href =http://www.epochconverter.com/>这个转换器,它给出了正确的日期。所以这是在几秒钟内。

I tried THIS converter for 1370001284 and it gives the right date. So it is in seconds.

但是我仍然收到错误的日期:

But I still get the wrong date for:

var substring = unix_timestamp.replace("/Date(", "");
substring = substring.replace("000+0200)/", "");
var date = new Date();
date.setSeconds(substring);
//var formatted = t.format("dd.mm.yyyy hh:MM:ss");
return date;

编辑解决方案:适用于:

EDIT Solution: Works for:

var substring = unix_timestamp.replace("/Date(", "");
substring = substring.replace("000+0200)/", "");
var date = new Date(substring * 1000);
return date;


推荐答案

Unix时间戳是自1970年以来的秒数, 01-01 00:00:00 UTC。

A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC.

+0200 的存在意味着数字字符串不是一个Unix时间戳,因为它包含时区调整信息。您需要单独处理。

The presence of the +0200 means the numeric string is not a Unix timestamp as it contains timezone adjustment information. You need to handle that separately.

如果您的时间戳记字符串以毫秒为单位,则可以使用毫秒构造函数和 Moment.js 将日期格式化成字符串:

If your timestamp string is in milliseconds, then you can use the milliseconds constructor and Moment.js to format the date into a string:

var t = new Date( 1370001284000 );
var formatted = t.format("dd.mm.yyyy hh:MM:ss");

如果您的时间戳字符串为秒,则使用 setSeconds

If your timestamp string is in seconds, then use setSeconds:

var t = new Date();
t.setSeconds( 1370001284 );
var formatted = t.format("dd.mm.yyyy hh:MM:ss");

注意我使用 t.format 来使用 Moment.js ,它不是JavaScript标准的一部分 Date 原型。

Note my use of t.format comes from using Moment.js, it is not part of JavaScript's standard Date prototype.

这篇关于从unix时间戳到datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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