![](/img/trans.png)
[英]How to Get Only Day Name or Number in a Week in JavaScript Date()
[英]How do I get the date to print only the day of the week?
如何使用JS只打印星期几。 还是一天和一个月?
我当时在玩一些功能,但我只能得到整个日期。
let today = new Date()
today.getDate()
let tomorrow = new Date();
tomorrow.getDay(today.getDate()+1)
然后,我将不得不使用该变量作为react组件中的props,它应该是一个字符串。 那么我应该使用toUTCstring吗?
getDay
接受任何参数。 您正在寻找setDate
将日期设置为明天,然后使用不带参数的getDay
:
let tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); let days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] console.log('tomorrow is: ' + days[tomorrow.getDay()])
您可以使用getDay()
方法。 这将返回一个数字。 您可以使用该数字获取日期。 像这样
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
let date = new Date();
var day_of_week = date.getDay();
var day_name = days[day_of_week];
您可以使用toLocaleString
的weekday
选项:
mydateobject.toLocaleString("en", { weekday: "long" })
可以通过类似的方式获取月份名称:
mydateobject.toLocaleString("en", { month: "long" })
javascript Date对象具有许多获取所需内容的方法:您可以使用getDay()获取星期几,并使用getMonth()获取月份。
要将其作为字符串参数传递,我相信最好是使用toISOString(),并且可以将此字符串用作另一边的Date构造函数的参数。
为了处理日期,我建议使用moment js库
您可以使用npm install moment
安装它,然后
moment().format('E');
要么
moment().utc.().format('E');
或只是moment().day()
使用Date.toDateString()可以将其格式化为dd mmm yy(或您想要的任何方式):
let date = new Date
str = date.toDateString() // 'Mon May 06 2019
let arr = str.split(" ") // ['Mon', 'May', '06', '2019']
let formatted = parseInt(arr[2]).toString() + " " + arr[1] + " " + arr[3] //6 May 2019
console.log(formatted) //6 May 2019
使用Date.toLocaleString()给出工作日:
let date = new Date
let weekdayLong = date.toLocaleString('en-gb', {weekday: 'long'}) //Monday
let weekdayShort = date.toLocaleString('en-gb', {weekday: 'short'}) //Mon
看起来toDateString
将始终返回一天中的3个字母(如果是星期几),因此您可以:
// Today
new Date().toDateString().substring(0,3)
// Tomorrow
new Date(Date.now()+24*3600*1e3).toDateString().substring(0,3)
或者,获取数字(从零开始):
// Today
new Date().getDay()
// Tomorrow
new Date(Date.now()+24*3600*1e3).getDay()
如果使用momentjs库,则可以使用let day = moment(tomorrow).format('dddd');
let tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(tomorrow)
let day = moment(tomorrow).format('dddd');
console.log(day);
let tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); console.log(tomorrow) let day = moment(tomorrow).format('dddd'); console.log(day);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.