Operation With Dates In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Operation With Dates In JavaScript.
Operation With Dates In JavaScript
JavaScript provides a number of built-in functions and methods for working with dates. Here are some examples:
Creating a new date object:
const now = new Date();
const specificDate = new Date(2022, 2, 14);
const specificDateTime = new Date(2022, 2, 14, 10, 30, 0);
Output
March 14, 2022
March 14, 2022, 10:30:00 AM
Getting various components of a date:
const date = new Date();
const year = date.getFullYear(); // 2023
const month = date.getMonth(); // 1 (February is 1, not 0)
const day = date.getDate(); // 17
const hour = date.getHours(); // 15
const minute = date.getMinutes(); // 30
const second = date.getSeconds(); // 0
const millisecond = date.getMilliseconds(); // 0
const weekday = date.getDay(); // 4 (Thursday is 4, not 0)
Setting various components of a date:
const date = new Date();
date.setFullYear(2022);
date.setMonth(2);
date.setDate(14);
date.setHours(10);
date.setMinutes(30);
date.setSeconds(0);
date.setMilliseconds(0);
Converting a date to a string:
const date = new Date();
const dateString = date.toString();
const isoString = date.toISOString();
Output
“Thu Feb 17 2023 15:30:00 GMT-0800 (Pacific Standard Time)”
“2023-02-18T00:30:00.000Z”
Comparing dates:
const date1 = new Date(2023, 2, 14);
const date2 = new Date(2022, 1, 1);
if (date1 > date2) {
console.log("date1 is later than date2");
}
These are just a few examples of the many operations you can perform with dates in JavaScript. For more information, you can refer to the JavaScript documentation on dates and times.
Conclusion
If you liked this post Operation With Dates In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.