Understanding Date and Time in JavaScript
Understanding Date and Time in JavaScript
JavaScript provides built-in functions to work with date and time. In this tutorial, we will learn how to use these functions to work with date and time in JavaScript.
Getting Current Date and Time
To get the current date and time, we can use the Date() function in JavaScript. This function returns the current date and time as a string.
var currentDate = new Date(); document.write(currentDate);
This will output the current date and time in the following format:
Thu Mar 03 2023 12:35:00 GMT-0500 (Eastern Standard Time)
Working with Dates
To work with dates in JavaScript, we can create a new Date() object and specify the date we want to work with.
var christmas = new Date('December 25, 2023');
document.write(christmas);
This will output the date specified in the following format:
Mon Dec 25 2023 00:00:00 GMT-0500 (Eastern Standard Time)
We can also work with individual components of a date such as the day, month, and year using the built-in methods in JavaScript.
var date = new Date(); var day = date.getDate(); var month = date.getMonth() + 1; var year = date.getFullYear(); document.write(day + '/' + month + '/' + year);
This will output the current date in the following format:
3/3/2023
Working with Time
To work with time in JavaScript, we can create a new Date() object and specify the time we want to work with.
var time = new Date(); time.setHours(12); time.setMinutes(30); time.setSeconds(0); document.write(time);
This will output the time specified in the following format:
Fri Mar 03 2023 12:30:00 GMT-0500 (Eastern Standard Time)
We can also work with individual components of time such as hours, minutes, and seconds using the built-in methods in JavaScript.
var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); document.write(hours + ':' + minutes + ':' + seconds);
This will output the current time in the following format:
12:35:00
Conclusion
Working with date and time is an important aspect of web development. JavaScript provides built-in functions to make it easier to work with date and time. In this tutorial, we learned how to use these functions to work with date and time in JavaScript.
Комментарии
Отправить комментарий