简体   繁体   中英

Javascript - How to get year and month from a date?

 var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; for (var i=1; i<7; i++){ console.log(year + i); }

I want to get the output list:

202205

202206

202207

202208

202209

202210

202211

202212

...

202612

When we call getMonthList on date, I need to display January as 01. How to do that?

How to get the output as above in a dropdown list.

You could use Date.setMonth() to set tne month of each generated date, using Array.from() create a list of the dates.

We'd use String.padStart() to pad the month with a leading zero if necssary.

 // Change as necessary const startDate = new Date(2022, 4, 1); const count = 56; const dates = Array.from({length: count},(_,n) => { let date = new Date(startDate); date.setMonth(date.getMonth() + n); let month = String(date.getMonth() + 1).padStart(2, '0'); return `${date.getFullYear()}${month}`; }); console.log('Generated dates:', dates)
 .as-console-wrapper { max-height: 100% !important; top: 0; }

We can also acheive the same result with a do...while loop, in this case we'll specify the start and end date.

 const startDate = new Date(2022, 4, 1); const endDate = new Date(2026, 11, 1); let date = new Date(startDate); let dates = []; do { let month = String(date.getMonth() + 1).padStart(2, '0'); dates.push(`${date.getFullYear()}${month}`); date.setMonth(date.getMonth() + 1); } while (date <= endDate) console.log('Generated dates:', dates)
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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