Last Updated : Jul 1, 2023
These apps must display relevant times based on the user's current timezone, or calculate arrivals and departures, as well as start and end times.
Creating a Date Object.
<!DOCTYPE html> <html> <head></head> <body> <script> var today = new Date(); </script> </body> </html>
<!DOCTYPE html> <html> <head></head> <body> <script> var time = new Date(); var date = time.getFullYear()+'-'+(time.getMonth()+1)+'-'+time.getDate(); </script> </body> </html>
- To get the date in YYYY-MM-DD format, update the date test.html file and add the variable:
- The instructions on the second line are as follows: date.getFullYear() – Utilises the today variable to display the 4-digit year.
- date.getMonth()+1 – Gives outputs as the numerical month – the +1 converts the month from digital (0-11) to normal.
- date.getDate() – Gives output as the numerical day of the month.
- Change the sequence of the commands if you desire a different arrangement.
<!DOCTYPE html> <html> <head></head> <body> <script> var time = new Date(); var today= time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds(); </script> </body> </html>
- Edit your script to look like this to show the time in HH:MM:SS format:
- time.getHours() – This uses the today variable to display the current hour. This uses a 24-hour clock.
- time.getMinutes() – Displays the current minute reading.
- time.getSeconds() – Displays the current seconds reading.
Display the current date and time in their full format.
<!DOCTYPE html> <html> <head></head> <body> <script> var time = new Date(); var date = time.getFullYear()+'-'+(time.getMonth()+1)+'-'+time.getDate(); var today= time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds(); var dateTime = date+' '+time; </script> </body> </html>
- To show the entire date and time in the YYYY-MM-DD and HH:MM:SS formats, combine the two instructions. Make the following changes to your script:
- The final line joins the two bits of code together. This tells the system to show the entire date alongside the complete time.