简体   繁体   中英

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". I have script a script to do that but somehow it will not work.
See below is my cshtml code:

<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:

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

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