문제

I have a string which contains DateTime as "20140121230000" . If i try to convert this into a Date.

var oDate = new Date(20140121230000);

i'm getting the year as 2068! Is there a way to convert this into a Date which is of year 2014, month 01 Date 21 Time 23:00:00 ?

Is it possible to directly convert this without doing any parsing in the string ?

도움이 되었습니까?

해결책

Unless you use a library there is no way to convert the value without manually splitting the string.

var year   = +oDate.slice( 0, 4);
var month  = +oDate.slice( 4, 2) - 1; // Month is zero-based.
var day    = +oDate.slice( 6, 2); 

var hour   = +oDate.slice( 8, 2); 
var minute = +oDate.slice(10, 2); 
var second = +oDate.slice(12, 2);

// This will interpret the date as local time date.
var date = new Date(year, month, day, hour, minute, second);

// This will interpret the date as UTC date.
var utcDate = Date.UTC(year, month, day, hour, minute, second);

다른 팁

The constructor you used takes millisecond since 1st Jan, 1970, try using :

 var oDate = new Date(2014, 01, 21, 23, 00, 00, 00);

Note, month 01 will be Feb, not Jan.

Constructing a Date object with a string

new Date(string)

expects a date string that Date.parse can understand:

  • ISO 8601 (e.g. 2011-10-10T14:48:00), or
  • RFC2822 (e.g., Mon, 25 Dec 1995 13:30:00 GMT)

See MDN for more information on Date and Date.parse.

Yours is not a recognized format. You can either

  1. reformat the string to fit one of the formats above
  2. split the string manually and call Date with individual parameters, as in new Date(year, month, day, hour, minute, second, millisecond)
  3. use a library like moment.js

Using moment.js would look something like this:

moment("20140121230000", "YYYYDDMMHHmmss")

See moment.js string + format for more information about the format syntax.

Given '20140121230000', you can split it into bits and give it to the Date constructor:

function parseSToDate(s) {
  var b = s.match(/\d\d/g) || [];
  return new Date( (b[0] + b[1]), --b[2], b[3], b[4], b[5], b[6]);
}

console.log(parseSToDate('20140121230000'));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top