I'm trying to convert a string which represents a date in a milliseconds format like this :

var start = new Date(s);

However, it seems that it does not work because when I'm trying to display the date, I've got "Invalid date" as an error message.

What I would like to get is a date in this format :

Wed May 07 2014 09:00:00

Is this possible to do?

EDIT : The original value of the s variable is a string composed of 13 number (for instance : 13982762900000)

有帮助吗?

解决方案

Convert it to a numeric type instead of a string:

var date = new Date(parseInt(s, 10))

Explanation:

The input to the new Date() constructor is a string. This means new Date() will assume the input is "a ISO8601 string" instead of "Integer value representing the number of milliseconds", as described below.

According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date it should be an integer if the value shall be interpreted as "representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch)."

new Date()

has the following constructors (according to the link above):

new Date();
new Date(value);
new Date(dateString);
new Date(year, month, day, hour, minute, second, millisecond);

value (this is the constructor being used if you convert it to an integer value)

Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).

dateString (this was the constructor being called before)

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

其他提示

var date = new Date(parseInt(your_timestamp, 10));

A timestamp should have 13 digits.

Your example timestamp has 14 digits. Is that a mistake or the timestamp is actually wrong?

You could:

var date = new Date(parseInt(your_timestamp, 10) / 10);

Transform your string in integer with parseInt and it's working :

var start = new Date(parseInt(s, 10));

Live Demo


Reference

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top