How to get the day of week and the month of the year?
Asked Answered
E

15

171

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()?

Edwards answered 27/1, 2011 at 22:47 Comment(0)
S
303

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();
Stirps answered 27/1, 2011 at 22:50 Comment(4)
@Will: You're welcome. FYI, if you're going to be doing this frequently, you could easily prototype the functionality into the Date object. I'll update in a minute.Stirps
Localize your data and there's no need for one-language-only arrays! selectedLocale = 'en-us'; selectedDate.toLocaleString(selectedLocale, { month: "long" });Pappano
I did this just now but had to use Monday as the first element in the array, not Sunday. Still, works great.Mceachern
No, no ,no ,no. Just use the standard javascript Date class. No need for arrays or an extra library. See my answer: https://mcmap.net/q/142962/-how-to-get-the-day-of-week-and-the-month-of-the-yearMedawar
M
94

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);
Medawar answered 11/5, 2018 at 13:17 Comment(6)
@Medawar this is nice, but how do I manage to get only the weekday without the rest of the date part? I.E. I want saturday instead of saturday, 9th february 2019.Spiel
@Valdimir Nul: var prnDt = 'Printed on ' + new Date().toLocaleDateString('en-us', { weekday: 'long' }); console.log(prnDt);Medawar
Definitely the best way to do it.Nancienancy
@Vladimir There is an issue with Firefox, time is always displayed, then: new Date().toLocaleTimeString(language, { weekday: 'long'}).split(' ')[0]Dunlin
This just displays the time for me.Barre
This is the way.Subdiaconate
B
17

I think this's the best solution I found

new Date(payload.value).toLocaleString("en", { weekday: "long" })
Bumbailiff answered 27/4, 2021 at 8:42 Comment(0)
C
14

One thing you can also do is Extend date object to return Weekday by:

Date.prototype.getWeekDay = function() {
    var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    return weekday[this.getDay()];
}

so, you can only call date.getWeekDay();

Cannibalism answered 19/2, 2016 at 11:51 Comment(0)
C
9

As @L-Ray has already suggested, you can look into moment.js as well

Sample

var today = moment();
var result = {
  day: today.format("dddd"),
  month: today.format("MMM")
}

document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
Clamper answered 17/5, 2016 at 11:2 Comment(0)
T
9

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.

Long form:

const options = { weekday: 'long' };
const date = new Date();
console.log(date.toLocaleDateString('en-US', options));

One liner:

console.log(new Date().toLocaleDateString('en-US', { weekday: 'long' }));

Note: there are other language options for locale, but the one presented here for for US English

Touber answered 1/7, 2019 at 14:15 Comment(0)
C
6
var GetWeekDays = function (format) {
    var weekDays = {};

    var curDate = new Date();
    for (var i = 0; i < 7; ++i) {
        weekDays[curDate.getDay()] = curDate.toLocaleDateString('ru-RU', {
            weekday: format ? format : 'short'
        });

        curDate.setDate(curDate.getDate() + 1);
    }

    return weekDays;
};

me.GetMonthNames = function (format) {
    var monthNames = {};

    var curDate = new Date();
    for (var i = 0; i < 12; ++i) {
        monthNames[curDate.getMonth()] = curDate.toLocaleDateString('ru-RU', {
            month: format ? format : 'long'
        });

        curDate.setMonth(curDate.getMonth() + 1);
    }

    return monthNames;
};
Crabb answered 6/3, 2016 at 15:45 Comment(1)
ru-RU would be en-US (for American English) or en-GB (for British English).Ineligible
H
5

Unfortunately, Date object in javascript returns information about months only in numeric format. The faster thing you can do is to create an array of months (they are not supposed to change frequently!) and create a function which returns the name based on the number.

Something like this:

function getMonthNameByMonthNumber(mm) { 
   var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); 

   return months[mm]; 
}

Your code therefore becomes:

var prnDt = "Printed on Thursday, " + now.getDate() + " " + getMonthNameByMonthNumber(now.getMonth) + " "+  now.getFullYear() + " at " + h + ":" + m + ":" s;
Holcomb answered 27/1, 2011 at 22:57 Comment(1)
Don't use new Array() unless you have a reason to. The [] notation is much clearer and easier to understandSalgado
J
3

Using http://phrogz.net/JS/FormatDateTime_JS.txt you can just:

var now = new Date;
var prnDt = now.customFormat( "Printed on #DDDD#, #D# #MMMM# #YYYY# at #hhh#:#mm#:#ss#" );
Jay answered 27/1, 2011 at 22:53 Comment(0)
M
2

You can look at datejs which parses the localized date output for example.

The formatting may look like this, in your example:

new Date().toString('dddd, d MMMM yyyy at HH:mm:ss') 
Malorie answered 4/4, 2013 at 11:26 Comment(0)
S
2
  function currentDate() {
      var monthNames = [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
                     "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ];
      var days = ['SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY'];                       
      var today = new Date();
      var dd   = today.getDate();
      var mm   = monthNames[today.getMonth()]; 
      var yyyy = today.getFullYear();
      var day  = days[today.getDay()];
      today = 'Date is :' + dd + '-' + mm + '-' + yyyy;
      document.write(today +"<br>");
      document.write('Day is : ' + day );
  }
  currentDate();
Stealer answered 22/7, 2019 at 10:22 Comment(0)
A
1

That's simple. You can set option to display only week days in toLocaleDateString() to get the names. For example:

(new Date()).toLocaleDateString('en-US',{ weekday: 'long'}) will return only the day of the week. And (new Date()).toLocaleDateString('en-US',{ month: 'long'}) will return only the month of the year.

Aerophone answered 23/9, 2018 at 11:11 Comment(0)
D
1

We can use the below snippet if the week starts from 1: 'Monday',2: 'Tuesday', 3: 'Wednesday',4: 'Thursday', 5: 'Friday',6: 'Saturday',7:'Sunday'.

let weekDays = {
  1: 'Monday',
  2: 'Tuesday', 
  3: 'Wednesday',
  4: 'Thursday',
  5: 'Friday',
  6: 'Saturday',
  7:'Sunday'};
return weekDays[dt];
Dinge answered 23/5, 2021 at 8:12 Comment(1)
this could be simplified to a list in which the index is the number. like so let weekDays = ['Monday', 'Tuesday' ... ]Haematite
T
0
new Date().toUTCString()

might be good enough for your purposes. It formats the string as: Tue, 31 Dec 2024 23:59:59 GMT https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString

Territorialize answered 26/9, 2021 at 19:26 Comment(0)
W
-9

Write the Date = <script> document.write(Date()); </script>

Wildawildcat answered 7/5, 2020 at 21:34 Comment(2)
how is this the solution the OP's problem ?Distaff
This script captures the updated date and timeWildawildcat

© 2022 - 2025 — McMap. All rights reserved.