Free Web Development Online Tutorials, Learn to Code
JavaScript Date Function, JavaScript Date Time AM PM example, Capture Date Time in Javascript

JavaScript Date Function Example

In JavaScript we have Date object, which provides many built-in properties and methods to find different format of date and time.

JavaScript Date Methods

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

Javascript getDate() method

var d = new Date();
document.write("Date is" + d.getDate());<br />
// 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

var d = new Date();
document.write("Month is" + d.getMonth());<br />
// month result here

Javascript getFullYear() method
Use Javascript getFullYear() to get the year, not getYear()

var d = new Date();
document.write("Year is" + d.getFullYear());<br />
// year result here

Capture Current Time in JavaScript Example

To get the time in javascript you can concatinate getHours() getMinutes() getSeconds()

  • Javascript getHours() method
    var _date = new Date();
    document.writeln("Hours:"+ _date.getHours());
  • Javascript getMinutes() method
    var _date = new Date();
    document.writeln("Minutes:"+ _date.getMinutes());
  • Javascript getSeconds() method
    var _date = new Date();
    document.writeln("Seconds:"+ _date.getSeconds());
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>");            

// Current time result here

Javascript Date Time AM or PM Example

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.

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()));
JavaScript Date Time Examples

javascript Interview Questions Answers

Get Time AM PM in JavaScript
JavaScript Examples | JavaScript Online Course