1

In my html file I'm passing an array of objects with a date time to javascript like this

<script>
    var TimerEvents = @Html.Raw(Json.Encode(Model.PendingTimerEvents));
</script>

my 'TimerEvents' has an EventTime property that when I read in Javascript looks like this

"/Date(1521617700000)/"

and I want to get this value, whatever it is, into a Javascript Date() object. like this

var countDownDate = new Date(date here).getTime();

What is that format, and how would I do this?

user1186050
  • 12,296
  • 22
  • 123
  • 274

3 Answers3

0

the value you get is a milisecond representation of the date, I think the count starts at 1/1/1970.

Anyway here is a solution for formatting it: Converting milliseconds to a date (jQuery/JavaScript)

Ariel Haim
  • 86
  • 6
  • so basically I just pass in the number to the date function? Maybe I don't know how to use the immediate window in Visual Studio but I tried that and it returned undefined – user1186050 Mar 21 '18 at 07:53
  • 1
    Yes but what you are getting back is not a valid json result, it's a string, you'll have to first extract the miliseconds from it and pass it to a new Date object – Ariel Haim Mar 21 '18 at 07:57
0

Assuming that Model.PendingTimerEvents is a DateTime, you could just do:

 var TimerDate = new Date(@Model.PendingTimerEvents.Year, @Model.PendingTimerEvents.Month, @Model.PendingTimerEvents.Day, @Model.PendingTimerEvents.Hour, @Model.PendingTimerEvents.Minute, @Model.PendingTimerEvents.Second);
sheavens
  • 685
  • 7
  • 14
-1

You can extract the date with regex if you need to:

<script>
    var TimerEvents = @Html.Raw(Json.Encode(Model.PendingTimerEvents)); //"/Date(1521617700000)/" 
    var dateString = TimerEvents.match(/\d+/)[0] // "1521617700000"
    var date = new Date(+dateString); //convert to number
    console.log(date); // Wed Mar 21 2018 08:35:00 GMT+0100 (Mitteleuropäische Zeit)
</script>
Marco
  • 20,296
  • 6
  • 68
  • 109