Date and Time is one of the important topic in any programming language. In JavaScript also gives us some elegant ways to work with Date and Time.
Let us start with the below example.
<html> <body> <script> var x = new Date() document.write(x) </script> </body> </html>
Now, if we dissect the output,
So, with the below statement,
var x = new Date()
We get a datetime object, x that has Weekday, Month, Day, Year, Hour, Minute, Second and Timezone.
So, you got the date in clubbed format. Now, what if you want everything separately.
Well! JavaScript provides that way as well.
<html> <body> <script> var x = new Date() var year = x.getFullYear() var month = x.getMonth() var day = x.getDate() var hour = x.getHours() var minute = x.getMinutes() var second = x.getSeconds() var milliSecond = x.getMilliseconds() var weekday = x.getDay() document.write("The full format is ", x, "</br>") document.write("The year is ",year, "</br>") document.write("The month is ",month, "</br>") document.write("The day is ",day, "</br>") document.write("The hour is ",hour, "</br>") document.write("The minute is ",minute, "</br>") document.write("The second is ",second, "</br>") document.write("The millisecond is ",milliSecond, "</br>") document.write("The weekday is ",weekday, "</br>") </script> </body> </html>
Now, if you look at the above output, we have separated the clubbed formatted date.
To display the year, you need to invoke getFullYear() function.
var year = x.getFullYear()
Similar, logic applies for Month, Day, Hour, Minute, Second and Millisecond.