search
HomeWeb Front-endJS TutorialA simple horizontal javascript date control_time and date

The specific requirements are:
1. The date table fills up the page horizontally.
2. The date list of each month is displayed in a row horizontally, instead of displaying a box like many date controls on the Internet.
3. It is required that only year, month and day are optional. After selecting year or month, the corresponding date will be automatically updated (this is available in every date control).
4. The current year and month are displayed by default, the current date is highlighted, and the current week (week of the year) and day of the week are displayed.
5. After selecting a date, the current date will be highlighted, and the week and week display will be automatically updated.
6. Provide an interface to set the display style of a specific date.
6. Others are some interface display issues.

I thought it was just a date control. It’s relatively simple to make, but it’s especially horizontal. This is the first time I’ve heard of this need!
This is my first time writing something like a calendar. However, the trouble this time still lies in the calculation of weeks and the implementation of the interface for setting specific dates provided in the end. But after some analysis, it was solved very well. .
Main summary:
1. Use closures to hide internal functions and variables to prevent variable pollution. Finally, only one external interface is provided: setDateStyle
2. Calculating the number of days in February each year is not by judging leap years, but by judging whether February 29 exists. If it does not exist, it is 28 days.
3. To calculate the week, you must first calculate the day of the year that the current date is, and also consider the day of the week that January 1 of this year is, and then calculate it.
4. setDateStyle supports the input of a single date style and also supports the setting of multiple date styles. For style updates, arrays are mainly used to merge characters, and the indexOf method of strings is used to match and execute style settings.
5. CSS/JS/HTML are separated for easy maintenance. Function modularization facilitates reuse.

Copy code The code is as follows:

var logDateControl=(function(){
var curSelEl; //The currently selected date
var styleData=[],dataStyle={};
//Get the element with the specified id
var $=function(id){return document.getElementById(id)}
//Calculate the week of the specified date (default is the current date). This calculation method is more rigorous and accurate
var calWeek= function(dt){
var calDay=dt||new Date(); //The current time to be calculated
var firstDay=new Date(calDay.getFullYear(),0,1); //This year First day
//Calculate what day of the year it is now, 00:00 is the beginning of the day
var daysAll=Math.floor((calDay-firstDay)/1000/60/60/24) 1;
//What day of the week is the first day of the year
var firstDayWeekday=firstDay.getDay();
//The result is added to Monday of the first week to facilitate subsequent calculations
var diffDay=firstDayWeekday= =0?6:firstDayWeekday-1;
daysAll=daysAll diffDay;
return Math.ceil(daysAll/7); //Return the calculation result
}
//Calculate the number of days in a month, The year is 4 digits, the month is 1-2 digits (it should be in js date format such as 0 in January), the data is illegal and returns -1
var getDaysLen=function(year,month){
if(!( /^d{4}$/.test(year)&&/^d{1,2}$/.test(month))){return -1}
var monthDays=[31,28,31,30 ,31,30,31,31,30,31,30,31]
//Exists February 29th
if(month==1&&new Date(year,1,29).getMonth()== 1){monthDays[1]=29}
return monthDays[month]
}
//Display the date list, pass in the year and month (pass in the daily month.For example, February is passed in 2), and the display position
var displayDayList=function(year,month,pos){
var daysList=[];
var cells1=$(pos).rows[0] .cells;
var cells2=$(pos).rows[1].cells;
var daysArr=['日','一','二','三','四','五','六'];
//The following month-1 is converted to js month representation
for(var i=1,l=getDaysLen(year,--month) 1;i var wd=new Date(year,month,i).getDay();
cells1[i-1].className="";
if(wd==0||wd== 6){cells1[i-1].className="weekEnd";} //Add special style for weekends
//_oldCls saves the default style of the current date
cells1[i-1].innerText=daysArr[ wd];
cells2[i-1].className="unSelectDay";
cells2[i-1].setAttribute("_oldCls","unSelectDay");
cells2[i-1]. innerText=i>9?i:"0" i;
//Match user-defined style
var dtStr=year "|" (month 1) "|" i;
if((", " styleData.join(',') ",").indexOf("," dtStr ",")>-1){
cells2[i-1].className="unSelectDay " dataStyle[dtStr];
cells2[i-1].setAttribute("_oldCls","unSelectDay " dataStyle[dtStr]);
}
}
//If it is the current month, select the current day
if( new Date().getMonth()==month){
curSelEl=cells2[new Date().getDate()-1];
curSelEl.className="selectDay";
}
for(var j=i-1;j cells1[j].className=cells2[j].className="";
cells1[j].innerHTML=cells2[j] .innerHTML=" "; , you can directly pass in the DOM element that saves the date content, or the function determines based on the click position
var changeInfo=function(e){
e=e||event;
var el=e.target|| e.srcElement||e; //The last e: may be the incoming object
var day=el.innerText;
if(!/^d{1,2}$/.test(day) ) return; //If it is not a date, do nothing
//Restore the style of the previously selected date
if(curSelEl){curSelEl.className=curSelEl.getAttribute("_oldCls")}
curSelEl=el ; //Save the currently processed element
//Update the style of the selected date
el.className="selectDay";
var dt=new Date($("year").value,$(" month").value-1,day);
//Update information
$("day").value=day; //Date
$("weekday").value=['day ','One','Two','Three','Four','Five','Six'][dt.getDay()]; //Day of the week
$("week").value= calWeek(dt); //Week of the week
}
//Initialization
window.attachEvent("onload",function(){
var curDate=new Date(),curYear=curDate. getFullYear();
//Display the upper and lower ten years
for(var i=-10;i $("year").selectedIndex=10; //The current year is selected by default
$("month").selectedIndex=curDate.getMonth(); //The current month
$("day ").value=curDate.getDate(); //Current date
$("weekday").value=['日','一','二','三','四','五','Saturday'][curDate.getDay()]; //The current day of the week
$("week").value=calWeek(); //The current week
//Change the date or year Update date list
$("year").onchange=$("month").onchange=function(){displayDayList($("year").value,$("month").value,"daysList ")};
//Display a list of dates for the current month and highlight today's date
displayDayList(curDate.getFullYear(),curDate.getMonth() 1,"daysList");
});

//Interface for setting styles externally.
//Format: ([2007,10,12],"color:#f00") ([[2007,10,20],[2007,11,25]],"color:#00f")
//If the month is less than 10, do not bring 0
var setDateStyle=function(dateArr,style){
if(typeof dateArr!="object")return;
if(dateArr instanceof Array){
if(dateArr[0] instanceof Array){
for(var i=0;i }
var dataStr= dateArr.join('|');
styleData.push(dataStr);
dataStyle[dataStr]=style;
return;
}
}
//External interface
return {setDateStyle:setDateStyle}
})();
//Test style setting
logDateControl.setDateStyle([[2007,12,15],[2007,11,12]], "test");


[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute ]
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function