简体   繁体   English

如何根据月份中的数字获取日期名称

[英]How to Get The Name of Day Based on Number In Month

I know we can get the name of day in week by using a code like this 我知道我们可以使用以下代码获取星期几的名称

 var d = new Date(); var days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]; console.log(days[d.getDay()]); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

but I need to get name of days from 3 random numbers in current month 但我需要从当月的3个随机数中获取日期的名称

 var arr = []
 while(arr.length < 3){
   var randomnumber=Math.ceil(Math.random()*30)
   var found=false;
   for(var i=0;i<arr.length;i++){
    if(arr[i]==randomnumber){found=true;break}
  }
   if(!found)arr[arr.length]=randomnumber;
 }

can you please let me know how to do this in JS? 能否让我知道如何在JS中执行此操作?

All you need to do is to genrate a date and then use .getDay() to get a day between 0-6 ie from Sun to Sat . 您需要做的就是生成一个日期,然后使用.getDay()获得介于0 Sun to Sat 6之间的一天,即从Sun to Sat

function returnDay(d, m, y){
    var year = y | 2015; // Making y an optional param.
    var d = new Date(m+"/"+d+"/"+y); // Pass inside any date if you have.
    var days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
    return days[d.getDay()];
}

Now all you need to do is 现在您要做的就是

returnDay(16, 12, 2015); // Will return the day of 12/16/2015 (mm-dd-yy)

You can pass random date/month/year as well 您也可以传递随机的日期/月份/年份

If the requirement is only to find the day name (in English) for any day of the current month then it can be done in one line of code: 如果只需要查找当月任何一天的日期名称(英文),则可以用一行代码来完成:

 function getDay( day ) {
      return new Date((new Date()).setDate(day)).toDateString().split(' ').shift();
 }  

 // Test - DEC 2015 returns Tues, Mon, Thu, Fri
 console.info( getDay( 1 ));   
 console.info( getDay( 14 ));  
 console.info( getDay( 24 ));   
 console.info( getDay( 32 ));

You should do like 你应该喜欢

var d = new Date(),
    n = d.getMonth(),
    y = d.getFullYear();

var days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
//Create new date from your No and Current Month+Year
var newDate = new Date("YourRandNo" + n + y);    
console.log(days[newDate.getDay();]);

Ex. 例如 If Rand No is 21 then new date is " 21-12-2015 " and you can find day from date. 如果Rand No是21则新日期是“ 21-12-2015 ”,您可以找到日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM