37

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 ?

abc123
  • 17,855
  • 7
  • 52
  • 82
John John
  • 1
  • 72
  • 238
  • 501
  • This link should be helpful. http://www.webdevelopersnotes.com/tips/html/formatting_time_using_javascript.php3 – JNL Aug 30 '13 at 15:42
  • Someone asked something a lot like your question [here][1]. [1]: http://stackoverflow.com/questions/9709989/format-date-time-javascript – Kevin Rodal Aug 30 '13 at 15:46

14 Answers14

51

Demo using Console.Log

// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();

// log the date in the browser console
console.log('date:', n);
// log the time in the browser console
console.log('time:',time);

Demo using a DIV

// get a new date (locale machine date time)
var date = new Date();
// get the date as a string
var n = date.toDateString();
// get the time as a string
var time = date.toLocaleTimeString();

// find the html element with the id of time
// set the innerHTML of that element to the date a space the time
document.getElementById('time').innerHTML = n + ' ' + time;
<div id='time'></div>

Note: these functions aren't fully cross browser supported

Cross-Browser Functional

//Fri Aug 30 2013 4:36 pm
console.log(formatAMPM(new Date()));

//using your function (passing in date)
function formatAMPM(date) {
    // gets the hours
    var hours = date.getHours();
    // gets the day
    var days = date.getDay();
    // gets the month
    var minutes = date.getMinutes();
    // gets AM/PM
    var ampm = hours >= 12 ? 'pm' : 'am';
    // converts hours to 12 hour instead of 24 hour
    hours = hours % 12;
    // converts 0 (midnight) to 12
    hours = hours ? hours : 12; // the hour '0' should be '12'
    // converts minutes to have leading 0
    minutes = minutes < 10 ? '0'+ minutes : minutes;
  
    // the time string
    var time = hours + ':' + minutes + ' ' + ampm;
  
    // gets the match for the date string we want
    var match = date.toString().match(/\w{3} \w{3} \d{1,2} \d{4}/);
  
    //the result
    return match[0] + ' ' + time;
}
abc123
  • 17,855
  • 7
  • 52
  • 82
28

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

Josh
  • 2,835
  • 1
  • 21
  • 33
9

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' });
SaphuA
  • 3,092
  • 3
  • 39
  • 58
4

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

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

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
Nathan Strutz
  • 8,095
  • 1
  • 37
  • 48
3

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.

Harry
  • 87,580
  • 25
  • 202
  • 214
3
(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

3
(new Date()).toLocaleString()

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

m.e.conroy
  • 3,508
  • 25
  • 27
2

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

JNL
  • 4,683
  • 18
  • 29
2

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);
David Passmore
  • 6,089
  • 4
  • 46
  • 70
1
<!-- //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
nitin
  • 89
  • 10
1

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);
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78
1
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;
    }  
0
<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>
MS Wani
  • 31
  • 6
  • 2
    Please add an explanation to your answer to show how this answers the question. – Olivier De Meulder Nov 02 '17 at 13:33
  • Thanks @OlivierDeMeulder. It will display the date and time like this "Today is:Friday, 03/11/2017 10:31:38" – MS Wani Nov 03 '17 at 05:02
  • 1
    Hi there , thank you so much for contributing. I would suggest editing your answer and adding the explanation there. By providing clear and explanatory answers you will help the original poster and anybody that comes to this page later. – Olivier De Meulder Nov 03 '17 at 14:00
0
function showTime(){
    let date = new Date();
    let h = date.getHours(); 
    let m = date.getMinutes(); 
    let s = date.getSeconds(); 
    let d = date.getDate() ;
    let month = date.getMonth()+1;
    let year = date.getFullYear(); 
    let session = "AM";
    
    if(h == 0){
        h = 12;
    }
    
    if(h > 12){
        h = h - 12;
        session = "PM";
    }
    
    h = (h < 10) ? "0" + h : h;
    m = (m < 10) ? "0" + m : m;
    s = (s < 10) ? "0" + s : s;
    d = (d < 10) ? "0" + d : d;
    
    //Adds zero when less than 10.

    month = (month < 10) ? "0" + month : month;