日期日名

我需要显示一个日期的日期(如“05/23/2014”) ,我从第三方得到的名称。

我试过用 Date,但我只能得到日期。

怎样才能知道今天的名字?

264597 次浏览
var days = [
"Sunday",
"Monday",
"...", //etc
"Saturday"
];


console.log(days[new Date().getDay()]);

简单,阅读 JavaScript 手册中的 Date 对象

要使用 date 做其他事情,比如从中获取一个可读的字符串,我使用:

var d = new Date();
d.toLocaleString();

如果你只是想要时间或者日期的使用:

d.toLocaleTimeString();
d.toLocaleDateString();

您可以通过以下方法解析日期:

var d = new Date(dateToParse);

或者

var d = Date.parse(dateToParse);

不是最好的方法,使用数组代替。这只是一个替代方法。

Http://www.w3schools.com/jsref/jsref_getday.asp

var date = new Date();
var day = date.getDay();

你真的应该使用谷歌之前,你在这里发布。

由于其他人发布了 array 方法,我将向您展示一种使用 switch 语句的替代方法。

switch(day) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;


... rest of cases


default:
// do something
break;
}

然而,上面的方法是可行的,数组是更好的选择。您也可以使用 if()语句,但是一个 switch 语句会比几个 if 语句干净得多。

您可以使用 Date.getDay()方法,该方法对于星期天返回0,对于星期六返回6。因此,您可以简单地创建一个数组,其中包含日期名称的名称:

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(dateString);
var dayName = days[d.getDay()];

这里的 dateString是您从第三方 API 接收到的字符串。

或者,如果你想要日名的前3个字母,你可以使用 Date对象的内置 toString方法:

var d = new Date(dateString);
var dayName = d.toString().split(' ')[0];

这将采用 d.toString()输出中的第一个单词,即3个字母的日名。

let weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][new Date().getDay()]

你可以使用一个对象

var days = {
'Mon': 'Monday',
'etc..': 'etc..',
'Fri': 'Friday'
}


var date = new Date().toString().split(' ')[0]; //get day abreviation first
console.log(days[date]);

使用 由标准 JavaScriptDate 类提供的方法:

从日期获取日期名 :

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.

以数组的形式获取所有工作日:

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.

对于美国日期,使用‘ en-US’作为地区。

尝试使用以下代码:

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

这将以字符串格式提供日期名称。

使用 Date.toLocaleString ()方法:

new Date(dateString).toLocaleString('en-us', {weekday:'long'})

看看这个:

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일 목요일

资料来源: Mozilla 博士

最简单的方法:

var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayName = days[new Date().getDay()];

只要使用它:

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;
}

关于格式,你可以在这里阅读 文档日期时间格式

我不喜欢过于复杂的解决方案,如果有人想出更好的解决方案,请告诉我们:)

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>

解决方案一

var today = new Date();


var day = today.getDay();


var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];


var dayname = days[day];


document.write(dayname);

解决方案二

      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);

最短的一班

如果希望 Array 从周日开始,则将 UTC 日从6更改为5。

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')); 

解决办法只有一条:

const day = ["sunday","monday","tuesday","wednesday","thursday","friday","saturday"][new Date().getDay()]

要从任何给定日期获取日期,只需将日期传递到一个新的 Date 对象:

let date = new Date("01/05/2020");
let day = date.toLocaleString('en-us', {weekday: 'long'});
console.log(day);
// expected result = tuesday

要了解更多信息,请转到 mdn-date. Prototype.toLocaleString ()(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)

另一个选项是使用内置函数 Intl.DateTimeFormat,例如:

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>

var dayName =['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var day = dayName[new Date().getDay()];
console.log(day)

let weekday = new Date(dateString).toLocaleString('en-us', {weekday:'long'});
console.log('Weekday',weekday);
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"

此方法不要求您设置随机日期或事先知道 stringLocale。此方法独立于预定义的值。 可以从客户端检索区域设置。

在字符串区域设置中自动填充工作日数组。

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)

如果您还需要月份的区域名称;

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)

我现在是这样使用它的: (如您所见,我复制了当前日期,并将月份和日期设置为它们的第一次出现)

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

//使用函数解决此问题。 //一星期的日子是: “星期日”、“星期一”、“星期二”、“星期三”、“星期四”、“星期五”、“星期六”

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);