简体   繁体   中英

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

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");

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM