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

前端 未结 16 972
暗喜
暗喜 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:28

    With the accepted answer, January 1st would be displayed like this: 2017/1/1.

    If you prefer 2017/01/01, you can use:

    var dt = new Date();
    var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();
    
    0 讨论(0)
  • 2020-11-28 18:29

    ES2018 introduced regex capture groups which you can use to catch day, month and year:

    const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2});
    const results = REGEX.exec('2018-07-12');
    console.log(results.groups.year);
    console.log(results.groups.month);
    console.log(results.groups.day);
    

    Advantage of this approach is possiblity to catch day, month, year for non-standard string date formats.

    Ref. https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/

    0 讨论(0)
  • 2020-11-28 18:34

    Why not using the method toISOString() with slice or simply toLocaleDateString()?

    Check here:

    const d = new Date(); // today, now
    
    console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD
    
    console.log(d.toLocaleDateString('en-US')); // M/D/YYYY
    console.log(d.toLocaleDateString('de-DE')); // D.M.YYYY
    console.log(d.toLocaleDateString('pt-PT')); // DD/MM/YYYY

    0 讨论(0)
  • 2020-11-28 18:35

    Here is a cleaner way getting Year/Month/Day with template literals:

    var date = new Date();
    var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;
    console.log(formattedDate);

    0 讨论(0)
  • 2020-11-28 18:35

    You can simply use This one line code to get date in year-month-date format

    var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
    
    0 讨论(0)
  • 2020-11-28 18:36
    var dateObj = new Date();
    var month = dateObj.getUTCMonth() + 1; //months from 1-12
    var day = dateObj.getUTCDate();
    var year = dateObj.getUTCFullYear();
    
    newdate = year + "/" + month + "/" + day;
    

    or you can set new date and give the above values

    0 讨论(0)
提交回复
热议问题