[javascript] Javascript to display the current date and time

I have the following test Script to display the current date & time :-

document.getElementById("para1").innerHTML = formatAMPM();

function formatAMPM() {
    var date = new Date();
    var hours = date.getHours();
    var days = date.getDay(); 
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0'+minutes : minutes;
    var strTime = date + ' ' + hours + ':' + minutes + ' ' + ampm;
    return strTime;
}

which will display the following :-

Fri Aug 30 2013 16:36:10 GMT+0100 (GMT Standard Time) 4:36 pm

but i need to modify this to display only:-

Fri Aug 30 2013 4:36 pm

can anyone advice on how i can achieve this ?

This question is related to javascript

The answer is


Try this:

var d = new Date(),
    minutes = d.getMinutes().toString().length == 1 ? '0'+d.getMinutes() : d.getMinutes(),
    hours = d.getHours().toString().length == 1 ? '0'+d.getHours() : d.getHours(),
    ampm = d.getHours() >= 12 ? 'pm' : 'am',
    months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
    days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
return days[d.getDay()]+' '+months[d.getMonth()]+' '+d.getDate()+' '+d.getFullYear()+' '+hours+':'+minutes+ampm;

DEMO


var today = new Date(); 
    var dd = today.getDate(); 
    var mm = today.getMonth()+1;//January is 0! 
    var yyyy = today.getFullYear(); 
    var h = today.getHours();
       var m = today.getMinutes();
       var s = today.getSeconds();
    if(dd<10){dd='0'+dd} 
    if(mm<10){mm='0'+mm} 
    if(h<10){h='0'+h}
    if(m<10){m='0'+m} 
    if(s<10){s='0'+s}  
    onload = function(){ 
        $scope.currentTime=+dd+'/'+mm+'/'+yyyy+' '+h+':'+m+':'+s;
    }  

<!-- //Hide From Old Browsers



var d=new Date();
var y=d.getYear();
if (y < 1000)
 y+=1900;
var day=d.getDay();
var m=d.getMonth();
var daym=d.getDate();
if (daym<10)
 daym="0"+daym;
 var mon=new Array("January", "February", "March", "April", "May", "June", "July",  "August", "September", "October", "November", "December");
document.write("<font size='2' color='#660000'>"+mon[m]+" "+daym+", "+y+"</font>");

// End Hide -->


  Result :  November 08, 2014

Updated to use the more modern Luxon instead of MomentJS.

Don't reinvent the wheel. Use a tried and tested library do this for you, Luxon for example: https://moment.github.io/luxon/index.html

From their site:

https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html#instance-method-toLocaleString

//=> 'Thu, Apr 20, 11:27 AM'
DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });

<script>

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    var h = today.getHours();
    var m = today.getMinutes();
    var s = today.getSeconds();


    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }
    if (h < 10) { h = '0' + h }
    if (m < 10) { m = '0' + m }
    if (s < 10) { s = '0' + s }

    var ctoday = dd + '/' + mm + '/' + yyyy+ '\t' +h+ ':' +m+ ':' +s;
    var d = new Date()
    var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
    console.log("Today is " + weekday[d.getDay()])
    document.getElementById('time').innerHTML = '<span style="color:blue">' + weekday[d.getDay()] + ", " + ctoday + '</span>';
</script>
<div>
<span> Today is : <span id="time"> </span>
</div>

To return the client side date you can use the following javascript:

var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;

or in jQuery:

var d = new Date();
var month = d.getMonth()+1;
var date = d.getDate()+"."+month+"."+d.getFullYear();
$('#date').html(date);

equivalent to following PHP:

<?php date("j.n.Y"); ?>

To get equivalent to the following PHP (i.e. leading 0's):

<?php date("d.m.Y"); ?>

JavaScript:

var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;

if(day < 10){
    day = "0"+d.getDate();
}

if(month < 10){
    month = "0"+eval(d.getMonth()+1);
}

var date = day+"."+month+"."+d.getFullYear();
document.getElementById('date').innerHTML = date;

jQuery:

var d = new Date();
var day = d.getDate();
var month = d.getMonth()+1;

if(day < 10){
    day = "0"+d.getDate();
}

if(month < 10){
    month = "0"+eval(d.getMonth()+1);
}

var date = day+"."+month+"."+d.getFullYear();
$('#date').html(date);

(new Date()).toLocaleString()

Will output the date and time using your local format. For example: "5/1/2020, 10:35:41 AM"


The request was to format a date in this format:

Fri Aug 30 2013 4:36 pm

I strongly suggest that anyone who comes across this question should use JavaScript's Intl API to format your dates instead of trying to come up with your own preferred format.

Here's an example

_x000D_
_x000D_
let d = new Date();
let formatter = Intl.DateTimeFormat(
    "default", // a locale name; "default" chooses automatically
    {
        weekday: "short", 
        year: "numeric",
        month: "short",
        day: "numeric",
        hour: "numeric",
        minute: "numeric"
    }
);

console.log(formatter.format(d));
_x000D_
_x000D_
_x000D_

The output for me, in the en-US locale, is:

Wed, Sep 30, 2020, 5:04 PM

The output for someone in Mexico (es-MX), is:

miƩ., 30 de septiembre de 2020 17:23

Why is Intl better?

  1. It's native code, with no string manipulation, no extra frameworks required, just a browser from any time after 2013 (when this question was first posted)
    • Nothing to download
    • No frameworks to add
    • Native code runs faster
  2. Intl formats dates as appropriate for the user's locale, e.g. a user in a different country who would prefer to read the year before the month would see the appropriately formatted date

_x000D_
_x000D_
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Noon';
  } else {
    hour = 12;
    prepand = ' PM';
  }
}
if (hour === 0 && prepand === ' AM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Midnight';
  } else {
    hour = 12;
    prepand = ' AM';
  }
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
_x000D_
_x000D_
_x000D_


Demo using Console.Log

_x000D_
_x000D_
// get a new date (locale machine date time)_x000D_
var date = new Date();_x000D_
// get the date as a string_x000D_
var n = date.toDateString();_x000D_
// get the time as a string_x000D_
var time = date.toLocaleTimeString();_x000D_
_x000D_
// log the date in the browser console_x000D_
console.log('date:', n);_x000D_
// log the time in the browser console_x000D_
console.log('time:',time);
_x000D_
_x000D_
_x000D_

Demo using a DIV

_x000D_
_x000D_
// get a new date (locale machine date time)_x000D_
var date = new Date();_x000D_
// get the date as a string_x000D_
var n = date.toDateString();_x000D_
// get the time as a string_x000D_
var time = date.toLocaleTimeString();_x000D_
_x000D_
// find the html element with the id of time_x000D_
// set the innerHTML of that element to the date a space the time_x000D_
document.getElementById('time').innerHTML = n + ' ' + time;
_x000D_
<div id='time'></div>
_x000D_
_x000D_
_x000D_

Note: these functions aren't fully cross browser supported

Cross-Browser Functional

_x000D_
_x000D_
//Fri Aug 30 2013 4:36 pm_x000D_
console.log(formatAMPM(new Date()));_x000D_
_x000D_
//using your function (passing in date)_x000D_
function formatAMPM(date) {_x000D_
    // gets the hours_x000D_
    var hours = date.getHours();_x000D_
    // gets the day_x000D_
    var days = date.getDay();_x000D_
    // gets the month_x000D_
    var minutes = date.getMinutes();_x000D_
    // gets AM/PM_x000D_
    var ampm = hours >= 12 ? 'pm' : 'am';_x000D_
    // converts hours to 12 hour instead of 24 hour_x000D_
    hours = hours % 12;_x000D_
    // converts 0 (midnight) to 12_x000D_
    hours = hours ? hours : 12; // the hour '0' should be '12'_x000D_
    // converts minutes to have leading 0_x000D_
    minutes = minutes < 10 ? '0'+ minutes : minutes;_x000D_
  _x000D_
    // the time string_x000D_
    var time = hours + ':' + minutes + ' ' + ampm;_x000D_
  _x000D_
    // gets the match for the date string we want_x000D_
    var match = date.toString().match(/\w{3} \w{3} \d{1,2} \d{4}/);_x000D_
  _x000D_
    //the result_x000D_
    return match[0] + ' ' + time;_x000D_
}
_x000D_
_x000D_
_x000D_


Get the data you need and combine it in the String;

getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();

Check out : Working With Dates


You can try the below:

function formatAMPM() {
    var date = new Date();
    var currDate = date.getDate();
    var hours = date.getHours();
    var dayName = getDayName(date.getDay());
    var minutes = date.getMinutes();
    var monthName = getMonthName(date.getMonth());
    var year = date.getFullYear();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
    alert(strTime);
}

function getMonthName(month) {
    var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return ar[month];
}

function getDayName(day) {
    var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    return ar1[day];
}

EDIT: Refer here for a working demo.


(function(con) {
    var oDate = new Date();
    var nHrs = oDate.getHours();
    var nMin = oDate.getMinutes();
    var nDate = oDate.getDate();
    var nMnth = oDate.getMonth();
    var nYear = oDate.getFullYear();

    con.log(nDate + ' - ' + nMnth + ' - ' + nYear);
    con.log(nHrs + ' : ' + nMin);
})(console);

This produces an output like:

30 - 8 - 2013
21 : 30

Perhaps you may refer documentation on Date object at MDN for more information