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?

chuckd
  • 13,460
  • 29
  • 152
  • 331
  • Wouldn't it be easier to call an api endpoint, that returns properly encoded dates, instead of using the views model? – Marco Mar 21 '18 at 07:53
  • what's an API endpoint? – chuckd Mar 21 '18 at 07:54
  • I could format the date time on the server before I pass it to the client! Maybe I should do that? – chuckd Mar 21 '18 at 07:55
  • https://www.asp.net/web-api You can read it all here – Marco Mar 21 '18 at 07:55
  • ya I here ya about the API but that would be way more work for what I need here. I'm just doing a fetch and loading data into a page – chuckd Mar 21 '18 at 07:56
  • Probably a duplicate of [*ASP.NET MVC JsonResult Date Format*](https://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format). – RobG Mar 21 '18 at 08:05

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
  • 7
  • 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 – chuckd 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
  • 22,856
  • 9
  • 75
  • 124