Here I am receiving the array of dates like this from the API,
let dates = ["22/1/2022","22/7/2022","9/10/2018"]
From these dates, I need to get the most recent date i.e 22/07/2022.
I got the below example from a site, This code works correctly only if the date matches the format of YYYY/MM/DD.
CODE
function max_date(all_dates) {
var max_dt = all_dates[0],
max_dtObj = new Date(all_dates[0]);
all_dates.forEach(function (dt, index) {
if (new Date(dt) > max_dtObj) {
max_dt = dt;
max_dtObj = new Date(dt);
}
});
return max_dt;
}
console.log(max_date(["2015/02/01", "2022/02/02", "2023/01/03"]));
Can we use some packages like date-fns or momentjs . to get the desired result despite the date format (or) with JS itself its achievable?
Please let me know your solution for this.
With date-fns you can do it like
import { max, parse } from "date-fns"
const dates = ["22/1/2022","22/7/2022","9/10/2018"];
console.log(max(dates.map((d) => parse(d, "d/M/yyyy", new Date()))))
// returns Fri Jul 22 2022 00:00:00 GMT+0200 (Central European Summer Time)
You can use pure Javascript for the logic
Convert strings to dates
Use timestamps (by getTime()) to find max
Convert that max timestamp back to date or string
const dates = ["22/1/2022", "22/7/2022", "9/10/2018"]
const convertStringToDate = (dateString) => {
const [day, month, year] = dateString.split("/");
return new Date(year, month - 1, day);
}
function format(inputDate) {
let date, month, year;
date = inputDate.getDate();
month = inputDate.getMonth() + 1;
year = inputDate.getFullYear();
return `${date}/${month}/${year}`;
}
const timestamps = dates.map(date => convertStringToDate(date).getTime())
const max = Math.max(...timestamps)
console.log(format(new Date(max)))
Sorting in descending order and returning the first element will do the work.
let dates = ['22/1/2022', '22/7/2022', '9/10/2018'];
const latestDate = (dates) => {
dates.sort((a, b) => {
const date1 = new Date(a.split('/').reverse().join('-'));
const date2 = new Date(b.split('/').reverse().join('-'));
return date2 - date1;
});
// First el will be latest date
return dates[0];
};
console.log(latestDate(dates));
// Output: 22/7/2022
Desired return value should be a string formatted as dd-mm-yyyy.
Im trying to give a format date dd-mm-yyyy to ISOString and adding GMT but the code gives me this format. How can i do?
new Date().toISOString()
.replace(/T/, ' '). // replace T with a space
.replace(/\..+/, ''); // delete the dot and everything after
'2012-11-04 14:55:45'
im looking for 04-11-2012 date format
Using today's date (which as an ISO string is currently "2016-03-08T13:51:13.382Z"), you can do this:
new Date().toISOString().replace(/T.*/,'').split('-').reverse().join('-')
The output of this is:
-> "08-03-2016"
This:
Grabs the date.
Converts it to an ISO string.
Replaces the 'T' and everything after it.
Converts it into an array by splitting on any hyphen ('-') character. (["2016", "03", "08"])
Reverses the order of the array. (["08", "03", "2016"])
Joins the array back as a string, separating each value with a hyphen character.
Here is a demo using your date (2012-11-04T14:55:45.000Z) as input:
var input = "2012-11-04T14:55:45.000Z",
output;
output = new Date(input).toISOString().replace(/T.*/,'').split('-').reverse().join('-');
document.getElementById('input').innerHTML = input;
document.getElementById('output').innerHTML = output;
<p><strong>Input:</strong> <span id=input></span></p>
<p><strong>Output:</strong> <span id=output></span></p>
You can use new Date().toLocaleDateString("en-US"); to return only the date. This returns "3/8/2016" today.
new Date().toLocaleDateString().replace(/\//g, '-'); will change it to output with dashes. This will return "3-8-2016" today.
For your example '2012-11-04 14:55:45'
You can do: new Date('2012-11-04 14:55:45').toISOString().split('T')[0] in a single line :)
You can convert the local date into a UTC date by adding the timezone offset, then calling toLocaleDateString (British format) while replacing the slashes with dashes and removing the comma.
// Adapted from: https://stackoverflow.com/a/55571869/1762224
const toLocaleUTCDateString = (date, locales, options) =>
new Date(date.valueOf() + (date.getTimezoneOffset() * 6e4))
.toLocaleDateString(locales, options);
// 'en-GB' === 'dd/mm/yyyy'
const formatDate = date =>
toLocaleUTCDateString(date, 'en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
.replace(/\//g, '-').replace(/,/, '');
const date = new Date();
console.log({
'ISO-8601': date.toISOString(),
'Custom': formatDate(date)
});
.as-console-wrapper { top: 0; max-height: 100% !important; }
Alternatively, you can try parsing the ISO 8601 string:
const formatDate = _date =>
(([year, month, date, hour, minute, second, milliseconds]) =>
`${date}-${month}-${year} ${hour}:${minute}:${second}`)
(_date.toISOString().split(/[^\d]/g));
const date = new Date();
console.log({
'ISO-8601': date.toISOString(),
'Custom': formatDate(date)
});
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to get date as dd-mm-yyyy format,
You can use custom function to generate with day, month and full year metods of Date(), but day and month may return number less then 10, if date or month's number is less then 10, so you can check if it is, you add 0, otherwise you leave itself like following below:
const date = () => {
let d = new Date();
let day = d.getDate()
let month = d.getMonth()
return `${day < 10 ? "0" + day : day}-${month < 10 ? "0" + month : month}-${d.getFullYear()}`;
}
let el = document.querySelector('p');
el.innerText = date();
<p></p>
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.