[英]typescript - get the day name from a date
I tried to get the day name from a date, but with the date 27/02/2021
i get Invalid Date我试图从日期中获取日期名称,但日期为
27/02/2021
我得到 Invalid Date
new Date(exam.examDate).toLocaleString('fr-FR', { weekday: 'long' })
i tried to convert the date using datePipe but it return the below error我尝试使用 datePipe 转换日期,但它返回以下错误
Unable to convert "27/02/2021" into a date' for pipe 'DatePipe
无法将“27/02/2021”转换为 pipe 'DatePipe 的日期'
new Date(this.datePipe.transform(exam.examDate, "dd/MM/yyyy")).toLocaleString('fr-FR', { weekday: 'long' })
You can get a custom day name from Date
like:您可以从
Date
获取自定义日期名称,例如:
const names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const dayName = names[dateObject.getDay()];
const date = '27/02/2021'; const d = date.split('/'); const names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const dayName = names[new Date(d[2],d[1],d[0]).getDay()]; console.log(dayName);
This is because Date
expects MM/DD/YYYY
but you're passing DD/MM/YYYY
:这是因为
Date
期望MM/DD/YYYY
但您正在传递DD/MM/YYYY
:
const getDay = date => { const parts = date.split('/'); return new Date(+parts[2], +parts[1] - 1, +parts[0]).toString().split(' ')[0]; } console.log( getDay('27/02/2021') );
Using moment.js
:使用
moment.js
:
const getDay = date => moment(date, "DD/MM/YYYY").format('ddd'); console.log( getDay('27/02/2021') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
examDate = "27/02/2021"; date = examDate.split("/"); x = new Date(date[2], date[1] - 1, date[0]); // it prints "samedi" console.log(x.toLocaleString('fr-FR', { weekday: 'long' }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.