How to get year/month/day from a date object?

前端 未结 16 1059
暗喜
暗喜 2020-11-28 17:52

alert(dateObj) gives Wed Dec 30 2009 00:00:00 GMT+0800

How to get date in format 2009/12/30?

16条回答
  •  隐瞒了意图╮
    2020-11-28 18:48

    info

    If a 2 digit month and date is desired (2016/01/01 vs 2016/1/1)

    code

    var dateObj = new Date();
    var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
    var date = ('0' + dateObj.getDate()).slice(-2);
    var year = dateObj.getFullYear();
    var shortDate = year + '/' + month + '/' + date;
    alert(shortDate);
    

    output

    2016/10/06

    fiddle

    https://jsfiddle.net/Hastig/1xuu7z7h/

    credit

    More info from and credit to this answer

    more

    To learn more about .slice the try it yourself editor at w3schools helped me understand better how to use it.

提交回复
热议问题