Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




JAVASCRIPT - DATE & TIME


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.


Example :



<html>
<body>  
<script>
	
	var x = new Date()
	document.write(x)
	    
</script>      
</body>
</html>


Output :



  Wed Mar 10 2021 13:59:12 GMT+0530

Now, if we dissect the output,

java_Collections

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.


Example :



<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>


Output :



  The full format is Wed Mar 10 2021 14:11:00 GMT+0530
  The year is 2021
  The month is 2
  The day is 10
  The hour is 14
  The minute is 11
  The second is 0
  The millisecond is 640
  The weekday is 3

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.