Chương trình JavaScript để định dạng ngày

Trong ví dụ này, bạn sẽ học cách viết một chương trình JavaScript định dạng ngày tháng.

Để hiểu ví dụ này, bạn nên có kiến ​​thức về các chủ đề lập trình JavaScript sau:

  • Câu lệnh JavaScript if… else
  • Ngày và giờ JavaScript

Ví dụ 1: Định dạng Ngày

 // program to format the date // get current date let currentDate = new Date(); // get the day from the date let day = currentDate.getDate(); // get the month from the date // + 1 because month starts from 0 let month = currentDate.getMonth() + 1; // get the year from the date let year = currentDate.getFullYear(); // if day is less than 10, add 0 to make consistent format if (day < 10) ( day = '0' + day; ) // if month is less than 10, add 0 if (month < 10) ( month = '0' + month; ) // display in various formats const formattedDate1 = month + '/' + day + '/' + year; console.log(formattedDate1); const formattedDate2 = month + '-' + day + '-' + year; console.log(formattedDate2); const formattedDate3 = day + '-' + month + '-' + year; console.log(formattedDate3); const formattedDate4 = day + '/' + month + '/' + year; console.log(formattedDate4);

Đầu ra

 26/08/2020 26/08-2020 26-08-2020 26/08/2020

Trong ví dụ trên,

1. Đối new Date()tượng cho biết ngày và giờ hiện tại.

 let currentDate = new Date(); console.log(currentDate); // Output // Wed Aug 26 2020 10:45:25 GMT+0545 (+0545)

2. getDate()Phương thức trả về ngày kể từ ngày được chỉ định.

 let day = currentDate.getDate(); console.log(day); // 26

3. getMonth()Phương thức trả về tháng kể từ ngày được chỉ định.

 let month = currentDate.getMonth() + 1; console.log(month); // 8

4. 1 được thêm vào getMonth()phương thức vì tháng bắt đầu từ 0 . Do đó, tháng 1 là 0 , tháng 2 là 1 , v.v.

5. Trả getFullYear()về năm kể từ ngày được chỉ định.

 let year = currentDate.getFullYear(); console.log(year); // 2020

Sau đó, bạn có thể hiển thị ngày ở các định dạng khác nhau.

thú vị bài viết...