简体   繁体   中英

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

 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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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