Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

Javascript Date Function

JavaScript Date Methods

To get date in Javascript, you need to write new Date();

Javascript getDate() method

<script>
var d = new Date();
document.write("Date is" + d.getDate());<br /> </script>

// date result here

Javascript getMonth() method

The getMonth() method returns number (0-11) as the month of a date, so you may consider number+1
<script>
var d = new Date();
document.write("Month is" + d.getMonth());<br /> </script>

// month result here

Javascript getFullYear() method
Use Javascript getFullYear() to get the year, not getYear()
<script>
var d = new Date();
document.write("Year is" + d.getFullYear());<br /> </script>

// year result here

Javascript getHours() getMinutes() getSeconds() method
To get the time in javascript you can concatinate getHours() getMinutes() getSeconds()
<script>
var d = new Date();
document.write("Hour is " + d.getHours() +"</br>");
document.write("Minute is " + d.getMinutes() + "</br>");
document.write("Second is " + d.getSeconds() + "</br>");
</script>

// Current time result here


AM or PM in Javascript Time
Now you may have a question how to know if the time is AM or PM right ? You have to use some logic as given below.
<script>
function getAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // if the hour is '0' then should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
return strTime;
}
document.write("Current Time is " + getAMPM(new Date()));
</script>


Comment
Name Email Website
Subscribe
 
Javascript Date Function

JavaScript Tutorial

Get Time AM PM in JavaScript
Group Training