BoundForGlory
BoundForGlory

Reputation: 4427

Convert datetime from server to string javascript

ASP.NET MVC 5 .Net 4.6.1 c#

I set a date on the server like so:

    public JsonResult GetDate()
    {
        var date = DateTime.Now;
        return Json(date);
    }

When I call this method via ajax, the date is returned like so:

     Date(1464670800000)

I know I can format my date at the server, but i dont want to do that because the date format changes for different sections of the page, so i want to format the date client side. How do I convert that date object returned from the server to a formatted string (mm/dd/yy for instance) in javascript? Thanks

Upvotes: 1

Views: 12156

Answers (2)

Alon
Alon

Reputation: 2929

You can do it manually:

    function formatDate(timestamp){
        var x=new Date(timestamp);
        var dd = x.getDate();
        var mm = x.getMonth()+1;
        var yy = x.getFullYear();
        return dd +"/" + mm+"/" + yy;
     }
    console.log(formatDate(new Date()));

Or you can use moments.js lib.

http://momentjs.com/

moment(date).format("DD/mm/YY");

Upvotes: 4

Travis J
Travis J

Reputation: 82297

I tend to use a regex on these to only get the numbers

replace(/\D/g, ''))

And just pass your Date(1464670800000) through that and then into the new Date constructor and work with it from there.

console.log(
  new Date(+"Date(1464670800000)".replace(/\D/g, ''))
)
//or for example, use LocaleDate
console.log(
  new Date(+"Date(1464670800000)".replace(/\D/g, '')).toLocaleDateString()
)

(The + is converting the string to an int so that "1464670800000" just becomes 1464670800000 to conform to the Date constructor)

Upvotes: 2

Related Questions