简体   繁体   English

将日期时间从服务器转换为字符串javascript

[英]Convert datetime from server to string javascript

ASP.NET MVC 5 .Net 4.6.1 c# 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: 当我通过ajax调用此方法时,将返回日期,如下所示:

     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? 如何将从服务器返回的日期对象转换为JavaScript中的格式化字符串(例如,mm / dd / yy)? 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. 或者,您可以使用moments.js库。

http://momentjs.com/ 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. 只需将您的Date(1464670800000)通过,然后传递到new Date构造函数并从那里使用它即可。

 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) +将字符串转换为int,以便"1464670800000"变为1464670800000以符合Date构造函数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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