Obtain abbreviated names for the days of the week starting from Monday to Sunday using JavaScript

Is there a way to retrieve the abbreviated names of each day of the week in JavaScript, starting from Monday through Sunday?

Answer №1

Let's take a look at an illustration using a German locale:

const locale = "de-de";
const dayNames = [];
const formatter = new Intl.DateTimeFormat(locale, {
  weekday: 'long'
});
const today = new Date();
const startDay = 1; // Monday
for (let day = startDay; day < startDay + 7; day++) {
  const date = new Date(today);
  date.setDate(today.getDate() + ((day - today.getDay() + 7) % 7));
  const formattedParts = formatter.formatToParts(date);
  const dayName = formattedParts.find(part => part.type === 'weekday').value;
  dayNames.push(dayName);
}
console.log(dayNames);

Answer №2

Here is an illustration involving lengthy English names:

const language = "en-us";
const elaborateNames = [];
const formatter = new Intl.DateTimeFormat(language, {
  weekday: 'long'
});
const today = new Date();
const startDay = 1; // Monday
for (let day = startDay; day < startDay + 7; day++) {
  const date = new Date(today);
  date.setDate(today.getDate() + ((day - today.getDay() + 7) % 7));
  const formattedParts = formatter.formatToParts(date);
  const longName = formattedParts.find(part => part.type === 'weekday').value;
  elaborateNames.push(longName);
}
console.log(elaborateNames);

Answer №3

It appears that you may be overcomplicating the situation. One approach is to set the initial date for obtaining day names to the desired start day. Additionally, using toLocaleString can simplify the process and offer the same options as DateTimeFormat without added complexity.

Below is a straightforward version using a for loop:

function getShortWeekdayNames(lang) {
  let days = [];
  for (let d = new Date(2023,5,12), i=7; i; --i) {
    days.push(d.toLocaleString(lang, {weekday:'short'}));
    d.setDate(d.getDate() + 1);
  }
  return days;
}

console.log(getShortWeekdayNames('fr'));

Here is a more condensed one-liner version:

let getShortWeekdayNames = lang => new Array(7).fill(0).map((x, i) => new Date(1,0,i).toLocaleString(lang, {weekday:'short'}));

console.log(getShortWeekdayNames('ar'));

If you further experiment with it, you can allow the caller to specify the starting day of the week as the ECMAScript day number and use that during date initialization:

let getShortWeekdayNames = (lang, d=1) => new Array(7).fill(0).map((x, i) => new Date(1,3,i+d).toLocaleString(lang, {weekday:'short'}));

// Start with Monday (default)
console.log(getShortWeekdayNames('en').join());
// Start with Sunday
console.log(getShortWeekdayNames('en', 0).join());
// Start with Saturday
console.log(getShortWeekdayNames('en', 6).join());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customized style sheets created from JSON data for individual elements

One of the elements in the API requires dynamic rendering, and its style is provided as follows: "elementStyle": { "Width": "100", "Height": "100", "ThemeSize": "M", "TopMargin": "0", " ...

What could be causing my function to return undefined instead of an array?

I have been working on a function to query my database and retrieve specific details for the selected item. While it successfully finds the items, it seems to be returning undefined. var recipefunc = function(name) { Item.find({name: name}, function ...

Unable to retrieve the properties of a JavaScript object

Currently I am working on a React webApp project and encountering difficulties when trying to access data within a JavaScript Object. Below is the code snippet in question: const user_position = System.prototype.getUserPosition(); console.log({user ...

Tips for saving data after reading lines in Node.js

I am working on a project where I need to read data from an external text file into my function. How can I efficiently store each line of the file as a separate variable? const fs = require("fs"); const readline = require("readline"); const firstVariable ...

Using AJAX/jQuery to populate a SelectList in an MVC view

I have a C# MVC application where I am dynamically populating a dropdown based on a selected date using AJAX/jQuery. The action called retrieves a list of items for the chosen date. The issue I'm facing is that I've previously rendered a partial ...

Manipulating data in node.js as it arrives in separate chunks

Hey there, I am trying to make some changes to the data received from the server. All incoming data via the POST method is processed in chunks. <button id='helloButton'>Send hello!</button> <button id='whatsUpButton'>S ...

What is the proper way to utilize bootstrap dropdown menus?

I need to create a dropdown menu similar to the one shown in this image: I attempted to use code from the following URL: https://getbootstrap.com/docs/4.0/components/dropdowns/, but unfortunately, it did not work as expected even though I have installed B ...

Is it possible to use Material-UI Link along with react-router-dom Link?

Incorporating these two elements: import Link from '@material-ui/core/Link'; import { Link } from 'react-router-dom'; Is there a method to combine the Material-UI style with the features of react-router-dom? ...

Express.js code is experiencing difficulties with autocomplete functionalities

jQuery autocomplete code example [Express JS code for retrieving data][2\ Example of fetching data in Express JS ...

Looking for a way to transfer the value of a variable to a PHP variable using any script or code in PHP prior to submitting a form?

Within this form, the script dynamically updates the module dropdown list based on the selected project from the dropdown box. The value of the module list is captured in a text field with id='mm', and an alert box displays the value after each s ...

Configuring modules using Sass, CSS-Modules, Webpack, React, and TypeScript

I'm facing an issue with extracting types from my .scss files. I've tried various configurations and solutions, but nothing seems to work. Specifically, my goal is to utilize modules in a React app with TypeScript. Below is my webpack configura ...

I would greatly appreciate your assistance in deciphering the JavaScript code provided in the book "Ajax in Action"

While reading through the Ajax in Action book, I came across a code snippet that has left me with a couple of questions. As someone who is new to web programming and still getting to grips with JavaScript, I am hoping for some clarity on the following: ...

Tips for extracting dynamically loaded content from a website using Node.js and Selenium?

I'm currently encountering some challenges when trying to scrape a website that utilizes react for certain parts of its content, and I'm unsure about the reason behind my inability to extract the data. Below is the HTML structure of the website: ...

I used npm to install a package, but for some reason, it's not appearing in

When attempting to install jquery using npm, I entered the following command: npm install jquery However, upon opening the destination folder, it was empty. (The below text was copied from cmd) > C:\Users\mandar\Desktop\Mady> ...

Monaco Editor: Module 'monaco-editor' is missing despite being successfully installed

During the development of my desktop application with electron, I encountered an issue with installing Monaco Editor. After using npm install monaco-editor, running the application resulted in a message saying Cannot find module 'monaco-editor'. ...

Can default values be assigned to a DTO during initialization?

What is the method to assign default values when a query is empty? In the case where I have this DTO structure for a query: export class MyQuery { readonly myQueryItem: string; } If the request doesn't include any query, then myQuery.myQueryItem ...

Error: The javascript function is unable to execute because undefined is not recognized as a function

I've been struggling with an error in my "bubble sort" function that I wrote to organize a list of images. Whenever I run the function, I keep getting the message "Uncaught TypeError: undefined is not a function". Can anyone provide some guidance? $j ...

A variety of negative () DOM Selectors

I've been trying to select a specific node using two not clauses, but so far I haven't had any luck. What I'm attempting to achieve is selecting an element whose div contains the string 0008, but it's not 10008 and also does not contain ...

Counting consecutive sentences starting with "The" using Javascript

As a newcomer, I am attempting to create a code that can split a copied text into sentences and then identify if three or more consecutive sentences begin with the word "The". My goal is for the program to be flexible regardless of the number of sentence ...

Tips for adding a text input field within a dropdown menu

Could someone provide guidance on how to place an input text box within a dropdown without using bootstrap? I came across this image showing what I am looking for: https://i.stack.imgur.com/f7Vl9.png I prefer to achieve this using only HTML, CSS, and Jav ...