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?

5
  • 2
    If you have a Date object, why not just call getTime()? Commented Aug 3, 2017 at 10:11
  • 1
    I'm not sure I understand the question correctly, but once you have a date as an instance of Date, you can do date.valueOf() or Number(date) or even +date to get numeric timestamp, like in +new Date(). Commented Aug 3, 2017 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 minimal reproducible example. Commented Aug 3, 2017 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. Commented Aug 3, 2017 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. Commented Aug 3, 2017 at 10:39

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

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.
oops! I posted this anwser before the update
no worries my original post I was quite confused about what I was seeing ;)
try parseInt() then. e.g parseInt('/Date(1451606400000)/', replace(/[^0-9\.]/g, ''), 10)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.