Get date using javascript in this format [MM/DD/YY]

余生长醉 提交于 2019-11-27 18:27:15

问题



how can I get the date in this format [mm/dd/yy] using javascript. I am struggling to get the 'year' to a 2 digit figure as opposed to the full 4 digits.

Thanks!


回答1:


Try this:

HTML

<div id="output"></div>

JS

(function () {
    // Get current date
    var date = new Date();

    // Format day/month/year to two digits
    var formattedDate = ('0' + date.getDate()).slice(-2);
    var formattedMonth = ('0' + (date.getMonth() + 1)).slice(-2);
    var formattedYear = date.getFullYear().toString().substr(2,2);

    // Combine and format date string
    var dateString = formattedMonth + '/' + formattedDate + '/' + formattedYear;

    // Reference output DIV
    var output = document.querySelector('#output');

    // Output dateString
    output.innerHTML = dateString;
})();

Fiddle: http://jsfiddle.net/kboucher/4mLe1Lrd/




回答2:


var date = new Date();
var datestring = ("0" + (date.getMonth() + 1).toString()).substr(-2) + "/" + ("0" + date.getDate().toString()).substr(-2)  + "/" + (date.getFullYear().toString()).substr(2);

This guarantees 2 digit dates and months.




回答3:


How About this for the year

String(new Date().getFullYear()).substr(2)

And since you need your Month from 01 through 12 do this

var d = new Date("2013/8/3"); 
(d.getMonth() < 10 ? "0" : "") + (d.getMonth() + 1)

Do the same thing for days, Minutes and seconds

Working Demo



来源:https://stackoverflow.com/questions/13184067/get-date-using-javascript-in-this-format-mm-dd-yy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!