Js gets a small example of the number of weeks specified by the date and the day of the week
- 2020-03-30 03:28:42
- OfStack
When JS gets a date, it encounters the following requirement to get a week's date based on a week of a year. If the starting date is Thursday, the following week's Friday is one week.
The code is as follows:
function getNowFormatDate(theDate)
{
var day = theDate;
var Year = 0;
var Month = 0;
var Day = 0;
var CurrentDate = "";
//Initialization time
Year= day.getFullYear();//Internet explorer or firefox
Month= day.getMonth()+1;
Day = day.getDate();
CurrentDate += Year + "-";
if (Month >= 10 )
{
CurrentDate += Month + "-";
}
else
{
CurrentDate += "0" + Month + "-";
}
if (Day >= 10 )
{
CurrentDate += Day ;
}
else
{
CurrentDate += "0" + Day ;
}
return CurrentDate;
}
function isInOneYear(_year,_week){
if(_year == null || _year == '' || _week == null || _week == ''){
return true;
}
var theYear = getXDate(_year,_week,4).getFullYear();
if(theYear != _year){
return false;
}
return true;
}
//Gets the date range display
function getDateRange(_year,_week){
var beginDate;
var endDate;
if(_year == null || _year == '' || _week == null || _week == ''){
return "";
}
beginDate = getXDate(_year,_week,4);
endDate = getXDate(_year,(_week - 0 + 1),5);
return getNowFormatDate(beginDate) + " to "+ getNowFormatDate(endDate);
}
//This method takes the date of the weekDay of a year
function getXDate(year,weeks,weekDay){
//Construct a date object with the specified year and set the date to January 1 of that year
//Since the month in the computer starts at 0, there is the following construction
var date = new Date(year,"0","1");
//Gets the long integer time of this date object, date
var time = date.getTime();
//I'm going to offset this long shaping time by the time of week N
//Because the first week is the current week, there is :weeks-1, and so on
//7*24*3600000 is the number of milliseconds in a week.
time+=(weeks-1)*7*24*3600000;
//Reset the date object date to time
date.setTime(time);
return getNextDate(date,weekDay);
}
//This method gets the weekDay date of the week in which the nowDate is
function getNextDate(nowDate,weekDay){
//0 is Sunday,1 is Monday,...
weekDay%=7;
var day = nowDate.getDay();
var time = nowDate.getTime();
var sub = weekDay-day;
if(sub <= 0){
sub += 7;
}
time+=sub*24*3600000;
nowDate.setTime(time);
return nowDate;
}
For the first week of 2016, start from Thursday. The date range for the first week is 2016-01-07 to 2016-01-15
In providing a section of the call reference code:
//Date processing
function dateRange(){
var _year = $("#_year").val();
var _week = $("#_week").val();
if(isInOneYear(_year,_week)){
var showDate = getDateRange(_year,_week);
$("#_dateRange_import").html(showDate);
} else{
alert(_year+" In no "+_week+" Zhou, please choose again ");
$("#_week").val("");
}
}