I need to display the name of the day given a date (like "05/23/2014") which I get from a 3rd party.
I've tried using Date, but I only get the date.
What is the correct way to get the name of the day?
Use the methods provided by the standard JavaScript Date class:
Getting the day name from a date:
function getDayName(dateStr, locale)
{
var date = new Date(dateStr);
return date.toLocaleDateString(locale, { weekday: 'long' });
}
var dateStr = '05/23/2014';
var day = getDayName(dateStr, "nl-NL"); // Gives back 'Vrijdag' which is Dutch for Friday.
Getting all weekdays in an array:
function getWeekDays(locale)
{
var baseDate = new Date(Date.UTC(2017, 0, 2)); // just a Monday
var weekDays = [];
for(i = 0; i < 7; i++)
{
weekDays.push(baseDate.toLocaleDateString(locale, { weekday: 'long' }));
baseDate.setDate(baseDate.getDate() + 1);
}
return weekDays;
}
var weekDays = getWeekDays('nl-NL'); // Gives back { 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag', 'zondag'} which are the days of the week in Dutch.
For American dates use 'en-US' as locale.
You could use the Date.getDay() method, which returns 0 for sunday, up to 6 for saturday. So, you could simply create an array with the name for the day names:
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(dateString);
var dayName = days[d.getDay()];
Here dateString is the string you received from the third party API.
Alternatively, if you want the first 3 letters of the day name, you could use the Date object's built-in toString method:
var d = new Date(dateString);
var dayName = d.toString().split(' ')[0];
That will take the first word in the d.toString() output, which will be the 3-letter day name.
use the Date.toLocaleString() method :
new Date(dateString).toLocaleString('en-us', {weekday:'long'})
let weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][new Date().getDay()]
var days = [
"Sunday",
"Monday",
"...", //etc
"Saturday"
];
console.log(days[new Date().getDay()]);
Simple, read the Date object in JavaScript manual
To do other things with date, like get a readable string from it, I use:
var d = new Date();
d.toLocaleString();
If you just want time or date use:
d.toLocaleTimeString();
d.toLocaleDateString();
You can parse dates either by doing:
var d = new Date(dateToParse);
or
var d = Date.parse(dateToParse);
To get the day from any given date, just pass the date into a new Date object:
let date = new Date("01/05/2020");
let day = date.toLocaleString('en-us', {weekday: 'long'});
console.log(day);
// expected result = tuesday
To read more, go to mdn-date.prototype.toLocaleString()(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)
let weekday = new Date(dateString).toLocaleString('en-us', {weekday:'long'});
console.log('Weekday',weekday);
Take a look at this :
var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012
console.log(event.toLocaleDateString('ar-EG', options));
// expected output: الخميس، ٢٠ ديسمبر، ٢٠١٢
console.log(event.toLocaleDateString('ko-KR', options));
// expected output: 2012년 12월 20일 목요일
Source : Mozilla Doc
One line solution :
const day = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"][new Date().getDay()]
Easiest and simplest way:
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayName = days[new Date().getDay()];
var dayName =['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var day = dayName[new Date().getDay()];
console.log(day)
One more option is to use the inbuilt function Intl.DateTimeFormat, e.g.:
const getDayName = (dateString) =>
new Intl.DateTimeFormat('en-Us', { weekday: 'long' }).format(new Date(dateString));
<label for="inp">Enter a date string in the format "MM/DD/YYYY" or "YYYY-MM-DD" and press "OK":</label><br>
<input type="text" id="inp" value="01/31/2021">
<button onclick="alert(getDayName(document.getElementById('inp').value))">OK</button>
Try using this code:
var event = new Date();
var options = { weekday: 'long' };
console.log(event.toLocaleDateString('en-US', options));
this will give you the day name in string format.
I'm not a fan of over-complicated solutions if anyone else comes up with something better, please let us know :)
any-name.js
var today = new Date().toLocaleDateString(undefined, {
day: '2-digit',
month: '2-digit',
year: 'numeric',
weekday: 'long'
});
any-name.html
<script>
document.write(today);
</script>
Shortest one liner
Change the UTC day from 6 to 5 if you want Array to start from Sunday.
const getWeekDays = (locale) => [...Array(7).keys()].map((v)=>new Date(Date.UTC(1970, 0, 6+v)).toLocaleDateString(locale, { weekday: 'long' }));
console.log(getWeekDays('de-DE'));
This method doesn't require you to set a random date or know the stringLocale beforehand. This method is independent from predefined values.
The locale can be retrieved from the client.
Automatically fill the weekdays array in the string locale.
const locale = 'en-US' // Change this based on client settings
const date = new Date()
const weekdays = []
while(!weekdays[date.getDay()]) {
weekdays[date.getDay()] = date.toLocaleString(locale, { weekday: 'long'})
date.setDate(date.getDate() + 1)
}
console.log(weekdays)
If you want the locale names for the months as well;
const locale = 'en-US' // Change this based on client settings
const date = new Date()
date.setMonth(0) // Not strictly needed, but why not..
date.setDate(1) // Needed because if current date is >= 29, the month Feb can get skipped.
const months = []
while(!months[date.getMonth()]) {
months[date.getMonth()] = date.toLocaleString(locale, { month: 'long'})
date.setMonth(date.getMonth() + 1)
}
console.log(months)
I currently use it like this:
(As you can see, I make a clone of the current date and set the month and date to their first occurance)
const date = new Date()
let locale = navigator.languages
? navigator.languages[0]
: (navigator.language || navigator.userLanguage)
let clone = new Date(date.getFullYear(), 0, 1, 0, 0, 0, 0)
let weekdays = []
while (!weekdays[clone.getDay()]) {
weekdays[clone.getDay()] = {
index: clone.getDay(),
long: clone.toLocaleString(locale, { weekday: 'long' }),
short: clone.toLocaleString(locale, { weekday: 'short' })
}
clone.setDate(clone.getDate() + 1)
}
clone.setDate(clone.getDate() - weekdays.length) // Reset
let months = []
while (!months[clone.getMonth()]) {
months[clone.getMonth()] = {
index: clone.getMonth(),
long: clone.toLocaleString(locale, { month: 'long' }),
short: clone.toLocaleString(locale, { month: 'short' })
}
clone.setMonth(clone.getMonth() + 1)
}
clone.setMonth(clone.getMonth() - months.length) // Reset
let hours = []
while (!hours[clone.getHours()]) {
hours[clone.getHours()] = {
index: clone.getHours(),
hour24: clone.toLocaleTimeString(locale, { hour12: false, hour: '2-digit', minute: '2-digit' }),
hour12: clone.toLocaleTimeString(locale, { hour12: true, hour: 'numeric' })
}
clone.setHours(clone.getHours() + 1)
}
clone.setHours(clone.getHours() - hours.length) // Reset
console.log(locale)
console.log(weekdays)
console.log(months)
console.log(hours)
console.log(clone.toLocaleString())
Solution No.1
var today = new Date();
var day = today.getDay();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var dayname = days[day];
document.write(dayname);
Solution No.2
var today = new Date();
var day = today.getDay();
switch(day){
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day ="Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thrusday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}
document.write(day);
you can use an object
var days = {
'Mon': 'Monday',
'etc..': 'etc..',
'Fri': 'Friday'
}
var date = new Date().toString().split(' ')[0]; //get day abreviation first
console.log(days[date]);
Just use it:
function getWeekDayNames(format = 'short', locale = 'ru') {
const names = [];
const date = new Date('2020-05-24');
let days = 7;
while (days !== 0) {
date.setDate(date.getDate() + 1);
names.push(date.toLocaleDateString(locale, { weekday: format }));
days--;
}
return names;
}
About formats you can read here Documentation DateTimeFormat
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(date.toLocaleDateString('de-DE', options));
// → "Donnerstag, 20. Dezember 2012"
// an application may want to use UTC and make that visible
options.timeZone = 'UTC';
options.timeZoneName = 'short';
console.log(date.toLocaleDateString('en-US', options));
// → "Thursday, December 20, 2012, UTC"
// Solve this problem with a function.
// The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
function getDayName(dateString) {
let dayName = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][new Date(dateString).getDay()];
return dayName;
}
let result = getDayName(10/12/2022);
console.log(result);
Not the best method, use an array instead. This is just an alternative method.
http://www.w3schools.com/jsref/jsref_getday.asp
var date = new Date();
var day = date.getDay();
You should really use google before you post here.
Since other people posted the array method I'll show you an alternative way using a switch statement.
switch(day) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
... rest of cases
default:
// do something
break;
}
The above works, however, the array is the better alternative. You may also use if() statements however a switch statement would be much cleaner then several if's.
Related
Is there a shorter way of converting date e.g. "2021-08-19" to "19 Aug 2021" or i need to every time create a new Date object??
const date = "2021-08-19";
const day = new Date(date).getDate()
const month = new Date(date).toLocaleString("en-US", {month: "short",})
const year = new Date(date).getFullYear()
console.log(day, month, year);
You could use UK format with some options for the date.
const
options = { year: 'numeric', month: 'short', day: 'numeric' },
date = "2021-08-19";
console.log(new Date(date).toLocaleString("en-UK", options));
In this date-picker, after selecting a date from the calendar, the selected date is outputted in the format dd-mm-yy, is there a way to output the date in the long format(Monday 21 February 2022.) There source of this date-picker is: https://code-boxx.com/simple-datepicker-pure-javascript-css/#sec-download
// CHOOSE A DATE
pick : (id, day) => {
// (C1) GET MONTH YEAR
let inst = picker.instances[id],
month = inst.hMonth.value,
year = inst.hYear.value;
// FORMAT & SET SELECTED DAY (DD-MM-YYYY)
if (+month<10) { month = "0" + month; }
if (+day<10) { day = "0" + day; }
inst.target.value = `${day}-${month}-${year}`;
// POPUP ONLY - CLOSE
if (inst.container === undefined) {
inst.hWrap.classList.remove("show");
}
// CALL ON PICK IF DEFINED
if (inst.onpick) { inst.onpick(); }
}
};
The date picker value will be in the format yyyy-MM-dd, you can parse this (using String.split() and pass the year, month and day to the Date() constructor.
We can then use Date.toLocaleString() to output the correct format:
function dateChanged() {
const dt = getDatePickerDate('date-input');
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
document.getElementById('output').innerHTML = dt.toLocaleDateString([], options);
}
function getDatePickerDate(elementId) {
const value = document.getElementById(elementId).value
const [year, month, day] = value.split('-');
return new Date(year, month - 1, day);
}
<input id='date-input' type="date" value="2022-02-21" onchange='dateChanged()'>
<p id='output'></p>
I'm using Pikaday.js like so:
new Pikaday({
field: document.getElementById('top-banner-datepicker'),
minDate: new Date()
I know that the answer lies in this example from the documentation:
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D/M/YYYY',
toString(date, format) {
// you should do formatting based on the passed format,
// but we will just return 'D/M/YYYY' for simplicity
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${day}/${month}/${year}`;
},
parse(dateString, format) {
// dateString is the result of `toString` method
const parts = dateString.split('/');
const day = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
const year = parseInt(parts[2], 10);
return new Date(year, month, day);
}
});
But I can't figure out how to use full day (Monday, Tuesday, Wednesday, etc) and full month names (January, February, etc) instead of the abbreviations (Mon, Tue, Wed... Jan, Feb, Mar... etc)
I don't want to use Moment.JS as it's a giant dependency.
Any help much appreciated!
Thank you
If you wish to format the datepicker field you could use toLocaleString().
For example if you want to get October instead of Oct:
date.toLocaleString('default', {
month: 'long' // use localestring month to get the long month
});
And if you want to get Sunday instead of Sun:
date.toLocaleString('default', { // use localestring weekday to get the long day
weekday: 'long'
});
Example snippet:
var picker = new Pikaday({
field: document.getElementById('datepicker'),
firstDay: 1,
minDate: new Date(),
maxDate: new Date(2020, 12, 31),
yearRange: [2000, 2020],
format: 'D-M-YYYY',
toString(date, format) {
console.log(date.toLocaleString('default', {
weekday: 'short' // use localestring weekday to get the short abbv of day
}));
console.log(date.toLocaleString('default', {
month: 'short' // use localestring weekday to get the short abbv of month
}));
// you should do formatting based on the passed format,
// but we will just return 'D/M/YYYY' for simplicity
const day = date.getDate();
const daylong = date.toLocaleString('default', { // use localestring weekday to get the long day
weekday: 'long'
});
const month = date.getMonth() + 1;
const monthlong = date.toLocaleString('default', {
month: 'long' // use localestring month to get the long month
});
const year = date.getFullYear();
return `${daylong}, ${monthlong}, ${day} ${year}`; // just format as you wish
}
});
#datepicker {
width: 200px;
}
<link href="https://pikaday.com/css/pikaday.css" rel="stylesheet" />
<script src="https://pikaday.com/pikaday.js"></script>
<label for="datepicker">Date:</label>
<input type="text" id="datepicker">
Pikaday Parsing
It's usually pretty easy getting dates into the correct format, but the tricky part usually is getting a date from a string. There's this warning in the Pikaday Read Me:
Be careful, though. If the formatted string that you return cannot be
correctly parsed by the Date.parse method (or by moment if it is
available), then you must provide your own parse function in the
config. This function will be passed the formatted string and the
format:
parse(dateString, format = 'YYYY-MM-DD')
Using Date.parse, can yield irregular results. This is where moment.js comes in handy as it can handle a variety of formats. The parsing function is used when a person directly types into the input field and maybe elsewhere.
Two approaches could involve using lightweight alternative to moment.js, or a custom formatter.
Approach 1: Lightweight Alternatives
You can search for moment.js alternatives. I found this repo that lists a few. For this example, I chose luxon, as it seems to be pretty small. You can see all the token it supports here: https://moment.github.io/luxon/docs/manual/parsing.html#table-of-tokens
To help out with parsing, I added this bit, which strips out weekday parsing, just in case if the weekday doesn't match the actual date:
if (format.startsWith('EEEE ')) {
format = format.split(' ').slice(1).join(' ');
dateString = dateString.split(' ').slice(1).join(' ');
}
Here's a working snippet:
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'EEEE LLLL d, yyyy',
toString(date, format) {
return luxon.DateTime.fromJSDate(date).toFormat(format);
},
parse(dateString, format) {
if (format.startsWith('EEEE ')) {
format = format.split(' ').slice(1).join(' ');
dateString = dateString.split(' ').slice(1).join(' ');
}
return luxon.DateTime.fromFormat(dateString, format).toJSDate();
}
});
div {
position: absolute;
bottom: 0;
}
#datepicker {
width: 250px;
}
<link href="https://pikaday.com/css/pikaday.css" rel="stylesheet" />
<script src="https://pikaday.com/pikaday.js"></script>
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>
<div><label for="datepicker">Date:</label>
<input type="text" id="datepicker">
</div>
Approach 2: Custom Formatter
For this answer I'll just use the format that you're asking for, but it gets tricky to parse a variety of formats.
Custom Names
To get custom names for months, you can just hard code them in:
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
Alternatively, since you want normal names, you can just programmatically generate them using Intl.DateTimeFormat. This is also useful if you want to have the months and weekdays show up in the user's locale:
var monthFormatter = new Intl.DateTimeFormat([], { month: 'long' });
var months = [... new Array(12)].map((d, i) => monthFormatter.format(new Date(2020, i, 1)));
var dayFormatter = new Intl.DateTimeFormat([], { weekday: 'long' });
var days = [... new Array(7)].map((d, i) =>dayFormatter.format(new Date(2020, 1, 2 + i)));
To access the names, you just use the corresponding index (remember that they're zero based though)
console.log(months[new Date().getMonth()]); // current month
console.log(days[new Date().getDay()]); // current day
Thus your custom format function looks something like this:
toString(date, format) {
// you should do formatting based on the passed format,
// but we will just return 'D/M/YYYY' for simplicity
const day = date.getDate();
const year = date.getFullYear();
const weekday = date.getDay();
const month = date.getMonth(); // remember, this is zero based!
return `${days[weekday]} ${months[month]} ${day}, ${year}`;
},
Date Parsing
Here's a custom tailored parsing function for the above format Weekday Month Day, Year:
parse(dateString, format) {
// split the string into the parts separated by a space
const parts = dateString.trim().split(' ');
var day, month, year, startIndex;
if (parts.length >= 3) {
if (parts.length >= 4) {
// if there's four parts, assume the first part is the weekday, which we don't need to use to convert it to a date
startIndex = 1; // skip the weekday
} else {
// if there's only three parts, assume that the weekday was omitted
startIndex = 0;
}
// look up the month from our prebuilt array. If it isn't found, it'll return -1, otherwise it will return the (zero based) numerical month.
month = months.indexOf(parts[startIndex]);
day = parts[startIndex + 1];
// if there's a comma after the day, remove it
if (day.endsWith(',')) {
day = day.substring(0, day.length - 1);
}
day = +day; // convert the string into a number
year = +parts[startIndex + 2]; // convert the string year into a number
}
if (parts.length < 3 // there is less than 3 parts
|| month === -1 // the month wasn't found
|| isNaN(day) // the day isn't a number
|| isNaN(year)) { // the year isn't a number
return Date.parse(dateString); // fall back to default Date parsing
}
return new Date(year, month, day);
}
All together, it looks like this:
var monthFormatter = new Intl.DateTimeFormat([], { month: 'long' });
var months = [... new Array(12)].map((d, i) => monthFormatter.format(new Date(2020, i, 1)))
var dayFormatter = new Intl.DateTimeFormat([], { weekday: 'long' });
var days = [... new Array(7)].map((d, i) =>dayFormatter.format(new Date(2020, 1, 2 + i)))
// Alternatively you can just hard code these:
// var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
// var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var picker = new Pikaday({
field: document.getElementById('datepicker'),
format: 'D/M/YYYY',
toString(date, format) {
// you should do formatting based on the passed format,
// but we will just return 'D/M/YYYY' for simplicity
const day = date.getDate();
const year = date.getFullYear();
const weekday = date.getDay();
const month = date.getMonth(); // remember, this is zero based!
return `${days[weekday]} ${months[month]} ${day}, ${year}`;
},
parse(dateString, format) {
// split the string into the parts separated by a space
const parts = dateString.trim().split(' ');
var day, month, year, startIndex;
if (parts.length >= 3) {
if (parts.length >= 4) {
// if there's four parts, assume the first part is the weekday, which we don't need to use to convert it to a date
startIndex = 1; // skip the weekday
} else {
// if there's only three parts, assume that the weekday was omitted
startIndex = 0;
}
// look up the month from our prebuilt array. If it isn't found, it'll return -1, otherwise it will return the (zero based) numerical month.
month = months.indexOf(parts[startIndex]);
day = parts[startIndex + 1];
// if there's a comma after the day, remove it
if (day.endsWith(',')) {
day = day.substring(0, day.length - 1);
}
day = +day; // convert the string into a number
year = +parts[startIndex + 2]; // convert the string year into a number
}
if (parts.length < 3 // there is less than 3 parts
|| month === -1 // the month wasn't found
|| isNaN(day) // the day isn't a number
|| isNaN(year)) { // the year isn't a number
return Date.parse(dateString); // fall back to default Date parsing
}
return new Date(year, month, day);
}
});
div {
position: absolute;
bottom: 0;
}
#datepicker {
width: 250px;
}
<link href="https://pikaday.com/css/pikaday.css" rel="stylesheet" />
<script src="https://pikaday.com/pikaday.js"></script>
<div><label for="datepicker">Date:</label>
<input type="text" id="datepicker">
</div>
Not going to write a book about it, because such default formats can be accomplished with Date, in particular method toLocaleDateString(), where long is the non-abbreviated weekday/month:
dateLocale: 'en-US',
dateOptions: {weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'},
toString(date, format) {
return date.toLocaleDateString(this.dateLocale, this.dateOptions);
},
Even if the formatting possibilities are rather limited alike that,
the advance still is, that supporting multi-locale is no problem.
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
I'm working on making a webpage that displays the next date for the Food Pantry. It happens on the second Friday of the month. I grabbed this current code from this question and I think I was able to modifiy it to fit my needs. However, I would like it to display in a 'April, 10th' format instead of '04/10/2020'. I have an extremely basic grasp of Javascript so if you explain it like I'm five would be helpful.
Also, if the second Friday is the current day, it would be great if it could say Today.
Thank you!
Date.prototype.nextsecondFriday = function (){
// Load the month.
var target = new Date(this.getFullYear(), this.getMonth(), 1, 0, 0, 0);
var today = new Date();
// Check to see if the 1st is on a Friday.
var isFriday = (target.getDay() == 1);
// Jump ahead two weeks from the 1st, and move back the appropriate number of days to reach the preceding Friday.
// i.e. If the 1st is a Thursday, we would move back three days.
var targetDate = 12 - (target.getDay() - 1);
// Quick adjustment if the 1st is a Friday.
if (isFriday) targetDate -= 4;
// Move to the second Friday in the month.
target.setDate(targetDate);
// Second Friday is before today's date, so find the second Friday next month.
if (today > target) {
//return "<em>" + target.toLocaleDateString() + " is in the past...</em>";
target.setMonth(target.getMonth() + 1);
return target.nextsecondFriday();
}
// Format and return string date of second Friday.
return target.toLocaleDateString();
}
var secondFridayDateString = new Date().nextsecondFriday();
document.getElementById("dynamicdate").innerHTML = secondFridayDateString;
<p>Our next food pantry is <span id="dynamicdate">Second Friday</span>.</p>
The below code find the second friday for any Date()
Date.prototype.nextsecondFriday = function() {
// get second firday for given month and year
const secondFriday = (year, month) => {
// first day of the month
let date = new Date(year, month, 1);
let dayDifference = 5 - date.getDay();
// get second friday of the month
if (dayDifference < 0) {
date.setDate(date.getDate() + (14 + (-1 * dayDifference)));
} else if (dayDifference >= 0) {
date.setDate(date.getDate() + 7 + dayDifference);
}
return date;
};
// format date to "April 10th"
const formatDate = (date) => {
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const month = months[date.getMonth()];
const day = date.getDate();
let suffix = 'th';
const j = day % 10,
k = day % 100;
if (j == 1 && k != 11) {
suffix = "st";
} else if (j == 2 && k != 12) {
suffix = "nd";
} else if (j == 3 && k != 13) {
suffix = "rd";
}
return `${month} ${day}${suffix}`;
};
let date = this;
let closestSecondSaturday;
do {
let secondFridayOfThisMonth = secondFriday(date.getFullYear(), date.getMonth());
if (secondFridayOfThisMonth.getDate() === date.getDate()) {
closestSecondSaturday = "Today";
} else if (secondFridayOfThisMonth.getDate() >= date.getDate()) {
closestSecondSaturday = formatDate(secondFridayOfThisMonth);
} else {
// if current date has crossed the second friday, move to the next month
date.setMonth(date.getMonth() + 1);
}
} while (!closestSecondSaturday)
return closestSecondSaturday;
};
// sample call
document.write(new Date().nextsecondFriday());
Try new Intl.DateTimeFormat('en-US', options).format(target)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
Date.prototype.nextsecondFriday = function (){
// Load the month.
var target = new Date(this.getFullYear(), this.getMonth(), 1, 0, 0, 0);
var today = new Date();
// Check to see if the 1st is on a Friday.
var isFriday = (target.getDay() == 1);
// Jump ahead two weeks from the 1st, and move back the appropriate number of days to reach the preceding Friday.
// i.e. If the 1st is a Thursday, we would move back three days.
var targetDate = 12 - (target.getDay() - 1);
// Quick adjustment if the 1st is a Friday.
if (isFriday) targetDate -= 4;
// Move to the second Friday in the month.
target.setDate(targetDate);
// Second Friday is before today's date, so find the second Friday next month.
if (today > target) {
//return "<em>" + target.toLocaleDateString() + " is in the past...</em>";
target.setMonth(target.getMonth() + 1);
return target.nextsecondFriday();
}
let options = { year: 'numeric', month: 'long', day: 'numeric' };
// Format and return string date of second Friday.
return new Intl.DateTimeFormat('en-US', options).format(target);
}
var secondFridayDateString = new Date().nextsecondFriday();
document.getElementById("dynamicdate").innerHTML = secondFridayDateString;
<p>Our next food pantry is <span id="dynamicdate">Second Friday</span>.</p>
I would modify the nextsecondFriday function to return the date object instead of a formatted string (just drop the toLocaleDateString() call).
Then write another function formatDate which receives a date and returns a formatted string.
Then call nextsecondFriday to get the date and format it usingformatDate.
The code for formatting (the formatDate function), if you require that specific format (the colon and the 'th' etc), would probably be something like:
const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
const monthOptions = { month: 'long' };
const dayOptions = { day: 'numeric' };
const formattedDate = event.toLocaleDateString('en-US', monthOptions) + ', ' + event.toLocaleDateString('en-US', dayOptions));
// then check event.getDay() and append 'st', 'nd', 'rd' or 'th' to formattedDate as needed
But if you can go with another format then just a single call to toLocaleDateString could be enough - check toLocaleDateString documentation on MDN for details.
See toDateString
you just have to change this statement
return target.toDateString();
options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
secondFridayDateString.toLocaleDateString("en-us", options)
you need to set the format, check that.
you can play with this in the console just doing:
let date = new Date()
options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
date.toLocaleDateString("en-us", options) //set your locale as you want i.e. es-ar or any locale
I use the toLocaleDateString method for formatting the date. This is how I do:
> var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
> var today = new Date();
> today.toLocaleDateString("fr-FR", options);
"mercredi 23 octobre 2019" //The output
In French the usual format of the date is rather like this:
Mercredi, 23 octobre 2019
The first letter of the day of the week in capital letters and a comma just after.
How can I adapt the code to this format?
Use moment.js:
moment().format('dddd, D MMMM YYYY');
See the formatting docs for more options
toLocaleDateString has very limited options for its output.
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.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
You'll want to define your own date string. Take a look at this question for a bunch of options.
How to format a JavaScript date
I found the this approach verry helpful and smart, the entire date is split into object attributes, so that you can tweak them in the way you want !
const mois = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre" ]
function frenchTodayDate() {
let today = new Date();
let year = today.getFullYear()
let dayNumber = today.getDate()
let month = mois[today.getMonth()]
let weekday = today.toLocaleDateString("fr-FR", { weekday: "long" });
return { weekday, dayNumber, month, year }
}
console.log(frenchTodayDate())
//=> { weekday: 'mercredi', dayNumber: 12, month: 'octobre', year: 2022 }
/*So let's say you want to print date according tothe french languages rules*/
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
const {weekday, dayNumber, month, year} = frenchTodayDate()
const aujourdhui = `${capitalize(weekday)}, le ${dayNumber} ${month} ${year}`
console.log(aujourdhui)
//=> Mercredi, le 12 octobre 2022
Thank you for your answers. Moment.js is a great library. Before migrating to Moment.js, I wrote a small code to work around the limitation of toLocaleDateString in order to get the format I want:
var options = {year: 'numeric', month: 'long', day: 'numeric' };
var opt_weekday = { weekday: 'long' };
var today = new Date();
var weekday = toTitleCase(today.toLocaleDateString("fr-FR", opt_weekday));
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
var the_date = weekday + ", " + today.toLocaleDateString("fr-FR", options)
// the output: "Jeudi, 24 octobre 2019"