简体   繁体   English

在javascript中更改日期格式

[英]Changing the date format in javascript

I want to change my date format from "MM/dd/yyyy hh:mm:ss AM" to "dd/mm/yyyy".我想将我的日期格式从“MM/dd/yyyy hh:mm:ss AM”更改为“dd/mm/yyyy”。 I have script a script to do that but somehow it will not work.我有一个脚本来做到这一点,但不知何故它不起作用。
See below is my cshtml code:见下面是我的cshtml代码:

<div>
<div id="homeWelcome">
    Welcome @ViewBag.User
</div>
<div>
    Please see below the list of books you have rented.
</div>
<div>
    <table>
        <thead>
            <tr>
                <th>Title</th>
                <th>Author</th>
                <th>Date Rented</th>
                <th>Return Date</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <th>@Html.DisplayFor(modelItem => item.Title)</th>
                    <th>@Html.DisplayFor(modelItem => item.Author)</th>
                    <th>dateFormat(@Html.DisplayFor(modelItem => item.DateRented))</th>
                    <th>@Html.DisplayFor(modelItem => item.ReturnDate)</th>
                </tr>
            }
        </tbody>
    </table>
</div>

My script:我的脚本:

<script type="text/javascript">
function dateFormat(d){
    d.toISOString().substring(0, 10);

    }
</script>

What could I be doing wrong?我可能做错了什么?

In order to use toISOString() you need to transform your date string into a Date object and then proceed to format it:为了使用toISOString()您需要将日期字符串转换为Date对象,然后对其进行格式化:

function dateFormat(d){
    var date = new Date(d);
    return [date.getMonth() + 1, date.getDate(), date.getFullYear()].join('/');
}

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

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