最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get day name in a date in node js - Stack Overflow

programmeradmin5浏览0评论

I have a date like this

2017-06-23 and my desired output is

Friday June 23 2017

 v.npi.appointment_dates[j] = date.toLocaleString('en-US', {year: 'numeric', month: 'long', day: 'numeric' });

But because of the day: 'numeric' I am missing the day name. Can anyone please help me?

I have a date like this

2017-06-23 and my desired output is

Friday June 23 2017

 v.npi.appointment_dates[j] = date.toLocaleString('en-US', {year: 'numeric', month: 'long', day: 'numeric' });

But because of the day: 'numeric' I am missing the day name. Can anyone please help me?

Share Improve this question edited Feb 14, 2021 at 12:25 Yann Bertrand 3,1141 gold badge25 silver badges40 bronze badges asked Jun 29, 2017 at 13:23 DusterDuster 993 silver badges9 bronze badges 6
  • Are you asking how to format a date using JS? – evolutionxbox Commented Jun 29, 2017 at 13:26
  • Have a look at the Date object and construct it on your own... – Jonas Wilms Commented Jun 29, 2017 at 13:28
  • Possible duplicate of How to format a JavaScript date – evolutionxbox Commented Jun 29, 2017 at 13:28
  • @evolutionxbox...yes – Duster Commented Jun 29, 2017 at 13:30
  • 1 It's not because of day: 'numeric' , it's because you've omitted weekday: 'long'. – RobG Commented Jun 29, 2017 at 22:32
 |  Show 1 more ment

2 Answers 2

Reset to default 5

You need to include weekday: 'long' in the options object:

var date = new Date();
console.log(date.toLocaleString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }));

If you want to adopt the the browser default language, use undefined:

var date = new Date();
console.log(date.toLocaleString(undefined, {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }));

Even with options support, the result of toLocaleString is still implementation dependent as the "locale" option is actually a language code, which may not be what the user expects even if they speak that language and the browser developers may not have chosen the expected format.

Here is the function you're looking for.

function getFormattedDate(date) {
  var dayNames = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
  var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

  var dayOfMonth = date.getDate()
  var dayOfWeekIndex = date.getDay()
  var monthIndex = date.getMonth()
  var year = date.getFullYear()

  return dayNames[dayOfWeekIndex] + ' ' + monthNames[monthIndex] + ' ' +  dayOfMonth + ' ' + year;
}

You should take a look at moment.js which will help you a lot with formatting and tons of other date issues.

发布评论

评论列表(0)

  1. 暂无评论