0

I have a JSON Object that when stringified looks like this [{"x":"/Date(1451606400000)/","y":877282.57}]

and I want to get the numeric part of the date 1451606400000

I can use regex, but is there an easier way involving parsing the date object? Perhaps I can construct a date from that value and then call a method to get the numeric component?

NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • 2
    If you have a `Date` object, why not just call `getTime()`? – Robby Cornelissen Aug 03 '17 at 10:11
  • 1
    I'm not sure I understand the question correctly, but once you have a date as an instance of [Date](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date), you can do `date.valueOf()` or `Number(date)` or even `+date` to get numeric timestamp, like in `+new Date()`. – rishat Aug 03 '17 at 10:11
  • 2
    "I have a date object" — Do you? Really? Or do you have a **string** with ASP.NET's idea of a JSON representation of a date in it? Or so you have exactly what you put in the question … which is a *regular expression literal*? Try providing a real [mcve]. – Quentin Aug 03 '17 at 10:12
  • Now, the opposite way, if you have a number that represents a timestamp, you can simply pass it as the first argument of Date constructor, like `new Date(date)`. The question is really unclear, sorry. – rishat Aug 03 '17 at 10:12
  • You could be right, I have expanded my answer. I assumed it was a date object but in order to ask the question I had to stringify it to try and see what I had. I assumed it was a date object. I'm still not entirely sure. – NibblyPig Aug 03 '17 at 10:39

1 Answers1

0

The question is quite confusing. When you say "I want to get the numeric part" I don't get it.. maybe you can be more explicit.

My anwser assummes you want to convert a string value to date object (again I might be wrong)

var dateString = "1451606400000"; //save string value to a varable
var dateInt = Number(dateString); //convert to number

//after converting to number parse the value into the date object.
//Note: parsing a string value direct will through an exception
var dateObject = new Date(dateInt);
console.log(dateObject); //Date 2016-01-01T00:00:00.000Z
Lucas
  • 1
  • 3
  • I thought I was explicit, I have `[{"x":"/Date(1451606400000)/","y":877282.57}]` and I want `1451606400000`. However I have solved it now using regex `x.match(/\d+/)[0] * 1)`. I thought it might be possible to do say, `y = new Date(x)` and then `y.toNumber()` or something but it doesn't look like it. – NibblyPig Aug 03 '17 at 11:10
  • oops! I posted this anwser before the update – Lucas Aug 03 '17 at 11:14
  • no worries my original post I was quite confused about what I was seeing ;) – NibblyPig Aug 03 '17 at 11:18
  • try parseInt() then. e.g parseInt('/Date(1451606400000)/', replace(/[^0-9\.]/g, ''), 10) – Lucas Aug 03 '17 at 11:25