Search code examples
javascriptangularjsdateionic2

Date Conversion CST in angular2


I am getting time like "DOB": "/Date(862588800000+0800)/" from json API but I have to convert it into something like Date Format : 04/28/2017 10:20:05 (MM/dd/yyyy HH:mm:sss) . Need help


Solution

  • You can start by parsing the value to a Date object, then formatting the output.

    The first number part appears to be a time value that is milliseconds since the epoch (1970-01-01), followed by a timezone offset in HHMM. Time values before the epoch are negative, so a regular expression to get the parts might be:

    /[+-]?\d+/g
    

    which should match both the time value and the offset.

    The time value can adjusted by the offset then used to create a Date (the value passed to the Date constructor needs to be a number, or it will be parsed as if it's a string):

    function parseDate(s) {
      // Get the parts
      var b = s.match(/[+-]?\d+/g);
    
      // If appears invalid, return invalid Date      
      if (!b || b.length != 2) return new Date(NaN);
      
      // Get sign of offset
      var sign = +b[1] < 0? -1 : 1;
    
      // Convert offset to milliseconds
      // Multiplication converts the strings to numbers so + adds
      var offset = sign * b[1].substr(1,2)*3.6e6 + b[1].substr(3,2)*6e4;
    
      // Adjust time value by offset, create a Date and return it
      // Subtraction also converts the time value to a number
      return new Date(b[0] - offset);
    }
    
    var s = '/Date(862588800000+0800)/';
    
    console.log(parseDate(s));

    The validation could also use a regular expression like:

    /\(-?\d+[+-]\d{4}\)/.test(s)
    

    As for formatting the Date, there are many questions about that already, see Where can I find documentation on formatting a date in JavaScript?