This question has already been answered:

Third-party service gives the date in this format:

/Date(1332446400000+0300)/ 

How in JavaScript can it be processed to normal?
It is clear that at the moment.js it is possible to pass a Dat(*) to the object and return what is needed, however:

 typeof /Date(1332446400000+0300)/ == "object" // true 

How can I get rid of too much so that I can safely convey at the moment such a format?
And I need to pre-check the variable for belonging to the Date.

 /Date(1332446400000+0300)/ instanceof Date; // false 

Reported as a duplicate by Grundy , aleksandr barakin , Denis , user194374, Mr. Black 24 Jul '16 at 5:45 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • var a = / Date (1332446400000 + 0300) / a.getDay () // error! - splincode
  • var a = / Date (1332446400000 + 0300) / new Date (parseInt (a.match (/ \ d + /) [0], 10)) writes this error var a = / Date (1332446400000 + 0300) / new Date (parseInt (/Date(1332446400000+0300)/.match (/\d+/)[007,10)) works this way, but I need to determine first that a is a Data type, I have different values ​​in a - splincode
  • Naturally, read carefully the answers, and first of all, the service returns a string, so when you try to surround yourself with quotes "/ Date (1332446400000 + 0300) /" , otherwise you try to work with a regular expression. - Grundy
  • aah, understand, thank you) write the answer, I note - splincode
  • var a = "/ Date (1332446400000 + 0300) /"; a.replace (new RegExp ("/", 'g'), ''); and how can I check now that this is a type of Date? after all, he simply considers this as a line - splincode

3 answers 3

Uncompromising parsing without regular expressions! :)

Hypothesis: that in brackets - milliseconds from the beginning of the Unix era and the time zone offset in the form of +HHMM (and can be -HHMM ).

We select everything inside the brackets, we divide by the sign "+" or "-", we construct the Date object from this time, subtracting its timezone offset (translate HH and MM in milliseconds).

 var myDate = parseDate("/Date(1332446400000+0300)/"); // из ответа сервера document.body.innerText = myDate.toString(); function parseDate( response) { if( response.substr(0,6) !== '/Date(' || response.substr(-2) !== ')/') { throw "Bad date format"; // какой-то не тот формат } var D = new Date(), parts, sign; if( !!~response.indexOf('+')) { sign = 1; parts = response.substr(6, response.length-8).split('+'); } else if( !!~response.indexOf('-')) { sign = -1; parts = response.substr(6, response.length-8).split('-'); } else { throw "No timezone offset"; } if( parts[1].length !== 4) throw "Bad timezone offset"; D.setTime( parseInt( parts[0], 10) - sign * 36E5 * parseInt( parts[1].substr(0,2), 10) - sign * 6E4 * parseInt( parts[1].substr(2,2), 10) ); return D; } 

    Such format Date.parse does not eat, for incorrectly.
    It is better to cut milliseconds, substitute as a number in the Date constructor and, possibly, play around with the UTC shift.
    True with the latest in JS problems, you can try a crutch.

     let str = '/Date(1332446400000+0300)/'; // Ваша строка // Выдираем длинное число миллисекунд и UTC let [, time, utc] = /Date\((\d+)((?:\+|-)0\d00)/.exec(str); // Валидный объект Date // Сначала создаём объект через мс // Потом возвращаем GTM представление и подменяем на нужный пояс, получается что-то типа: // Thu, 22 Mar 2012 20:00:00 GMT+0300 // Так Date.parse поймёт и переведёт в нужный пояс console.info(new Date(new Date(+time).toGMTString().replace('GMT', `GMT${utc}`))); 

       /Date(1332446400000+0300)/ 

      This is a regular expression. Try replacing all the slashes.

       "/Date(1332446400000+0300)/".replace(/\//g,''); 

      The output will be

       "Date(1332446400000+0300)" 

      As one of the options further penetrate the result through eval.

       var output = document.querySelector('div'); function validateDate(input){ var date; try { date = new Date(eval(input.replace(/\//g,''))); if (Object.prototype.toString.call(date) !== "[object Date]" || isNaN(+date)) throw new TypeError; } catch(e){ return false; } return date; }; output.innerHTML = validateDate('/Date(1332446400000+0300)/'); 
       <div></div> 

      As one option, run it through eval;

      • var a = eval ("Date (1332446400000 + 0300)"); a instanceof Date // false How can I check that a variable is of type Date? - splincode
      • new Date (eval ("Date (1332446400000 + 0300)")) instanceof Date // true - Petr Chalov
      • thanks)) but I’m going to have to check every new variable value then? - splincode pm
      • Updated code in response. If the date is not valid, it will return false, otherwise it will return the date itself (a Date object). - Petr Chalov