Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the day of week and the month of the year?

I don't know much about Javascript, and the other questions I found are related to operations on dates, not only getting the information as I need it.

Objective

I wish to get the date as below-formatted:

Printed on Thursday, 27 January 2011 at 17:42:21

So far, I got the following:

var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();

h = checkTime(h);
m = checkTime(m);
s = checkTime(s);

var prnDt = "Printed on Thursday, " + now.getDate() + " January " + now.getFullYear() + " at " + h + ":" + m + ":" s;

I now need to know how to get the day of week and the month of year (their names).

Is there a simple way to make it, or shall I consider using arrays where I would simply index to the right value using now.getMonth() and now.getDay()?

like image 980
Will Marcouiller Avatar asked Oct 10 '22 05:10

Will Marcouiller


2 Answers

Yes, you'll need arrays.

var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];

Or you can use the date.js library.


EDIT:

If you're going to use these frequently, you may want to extend Date.prototype for accessibility.

(function() {
    var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

    Date.prototype.getMonthName = function() {
        return months[ this.getMonth() ];
    };
    Date.prototype.getDayName = function() {
        return days[ this.getDay() ];
    };
})();

var now = new Date();

var day = now.getDayName();
var month = now.getMonthName();
like image 69
user113716 Avatar answered Dec 07 '22 03:12

user113716


Use the standard javascript Date class. No need for arrays. No need for extra libraries.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

var options = {  weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
var prnDt = 'Printed on ' + new Date().toLocaleTimeString('en-us', options);

console.log(prnDt);
like image 25
RWC Avatar answered Dec 07 '22 02:12

RWC