Mendapatkan Nombor Minggu dalam JavaScript Seperti tarikh PHP('W')
Fungsi tarikh('W') PHP mengembalikan nombor minggu ISO-8601 semasa tahun, bermula pada hari Isnin. Kita boleh mencapai hasil yang sama dalam JavaScript menggunakan pendekatan berikut:
Menggunakan Pustaka Luar
Pustaka luaran yang tersedia di pautan berikut boleh digunakan untuk mengira minggu ISO nombor tarikh yang diberikan:
Kod JavaScript Tersuai
Sebagai alternatif, kami boleh melaksanakan fungsi JavaScript tersuai untuk mengira nombor minggu:
/* For a given date, get the ISO week number * * Based on information at: * * THIS PAGE (DOMAIN EVEN) DOESN'T EXIST ANYMORE UNFORTUNATELY * http://www.merlyn.demon.co.uk/weekcalc.htm#WNR * * Algorithm is to find nearest thursday, it's year * is the year of the week number. Then get weeks * between that date and the first day of that year. * * Note that dates in one year can be weeks of previous * or next year, overlap is up to 3 days. * * e.g. 2014/12/29 is Monday in week 1 of 2015 * 2012/1/1 is Sunday in week 52 of 2011 */ function getWeekNumber(d) { // Copy date so don't modify original d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); // Set to nearest Thursday: current date + 4 - current day number // Make Sunday's day number 7 d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7)); // Get first day of year var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); // Calculate full weeks to nearest Thursday var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7); // Return array of year and week number return [d.getUTCFullYear(), weekNo]; } var result = getWeekNumber(new Date()); document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);
Penggunaan
var date = new Date("2018-01-15"); var weekNumber = getWeekNumber(date); console.log(weekNumber[1]); // Output: 3
Atas ialah kandungan terperinci Bagaimana untuk Mendapatkan Nombor Minggu ISO dalam JavaScript?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!