A simple horizontal JavaScript date control _ time Date

Source: Internet
Author: User
Tags getdate string indexof
The specific requirements are:
1. The date table is filled with pages horizontally.
2. Each month's list of dates is displayed horizontally in a row, rather than displaying a box like many date controls on the Web.
3, the request only month and year, select, the choice of years or months after the corresponding date automatically updated (This every date control has).
4, the default display current year, highlight the current date, and show the current week (the first weeks) and the day of the week.
5, select a date to highlight the current date, and automatically update the weekly and weekly display.
6, provide the interface, you can set a specific date display style.
6, the other is a number of interface display problems.

Think is a date control, doing is also relatively simple, but more especially horizontal, the first heard of this demand!
I am still the first time to write the Calendar class things, but this time the trouble is in the weekly calculation and finally provide a specific date of the implementation of the interface, but after some analysis is also a good solution.
Main summary:
1, the use of closures, hidden internal functions and variables to prevent variable pollution. Finally, only one external interface is provided: Setdatestyle
2. The calculation of the number of days per year February is not by judging leap years, but by judging whether February 29 exists or 28 days if it does not exist.
3, the calculation of the week to first calculate the current date is the first day of the year, but also consider January 1 this year is the week, and then calculate can be drawn.
4, Setdatestyle support the introduction of a single date style, but also support the setting of multiple date styles. For style updates, the main use of array merging character channeling, and using the string IndexOf method to match and perform style settings.
5, css/js/html phase separation, easy to maintain. function modularity facilitates reuse.
Copy Code code as follows:

var logdatecontrol= (function () {
var Curselel; The currently selected date
var styledata=[],datastyle={};
Gets the element of the specified ID
var $=function (id) {return document.getElementById (ID)}
Calculates the number of weeks of the specified date (the default is the current date), which is a more rigorous and accurate calculation method.
var calweek=function (DT) {
var calday=dt| |  New Date (); The current time to calculate
var firstday=new Date (Calday.getfullyear (), 0, 1); First day of the year
Calculation is currently the first day of the year, 00:00 for the start of the day
var Daysall=math.floor ((calday-firstday)/1000/60/60/24) +1;
Week of the first day of the year
var firstdayweekday=firstday.getday ();
This result is added to the first week of Monday, which is easy to calculate later
var diffday=firstdayweekday==0?6:firstdayweekday-1;
Daysall=daysall+diffday;
Return Math.ceil (DAYSALL/7); Return calculation results
}
Calculate one months days, years 4 digits, month 1-2 digits (should be JS date format such as January incoming 0), data illegal return-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 29
if (month==1&&new Date (year,1,29). getmonth () ==1) {monthdays[1]=29}
return Monthdays[month]
}
Displays a list of dates, passed into the year, month, in daily months. such as February incoming 2), and display location
var displaydaylist=function (Year,month,pos) {
var dayslist=[];
var cells1=$ (POS). Rows[0].cells;
var cells2=$ (POS). Rows[1].cells;
var daysarr=[' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six '];
The following month-1 is converted to the JS month representation
For (Var I=1,l=getdayslen (year,--Month) +1;i<l;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 styles for weekends
_oldcls saves the default style for 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 Custom 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 day
if (new Date (). getmonth () ==month) {
Curselel=cells2[new Date (). GetDate ()-1];
Curselel.classname= "Selectday";
}
for (Var j=i-1;j<31;j++) {
Cells1[j].classname=cells2[j].classname= "";
Cells1[j].innerhtml=cells2[j].innerhtml= "";
}
$ (POS). Onclick=function () {Changeinfo ()}
}
Depending on the value you select to process the week and week adjustments, you can directly pass in the DOM element that holds the date content, or the function is judged by the click position
var changeinfo=function (e) {
e=e| | Event
var el=e.target| | e.srcelement| |  E Last e: May be the object passed in
var Day=el.innertext;
if (!/^\d{1,2}$/.test) return; If it's not a date, do nothing.
Style of selected date before recovery
if (curselel) {Curselel.classname=curselel.getattribute ("_oldcls")}
Curselel=el; Save the currently processed element
Update styles for selected dates
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); The first few weeks
}
Class
Window.attachevent ("onload", function () {
var curdate=new Date (), curyear=curdate.getfullyear ();
Show up and down 10 years
for (Var i=-10;i<10;i++) {$ (' year '). Add (New Option (Curyear+i,curyear+i))}
$ ("year"). selectedindex=10; Select the current year by default
$ ("month"). Selectedindex=curdate.getmonth (); Current month
$ ("Day"). Value=curdate.getdate (); Current date
$ ("weekday"). value=[' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' Six '][curdate.getday ()]; Current day of the week
$ ("Week"). Value=calweek (); The current week in the first few weeks
Change date or year update date list
$ (' year '). onchange=$ ("month"). Onchange=function () {displaydaylist ($ ("year"). value,$ ("month"). Value, "Dayslist"} ;
Displays a list of the month's dates and highlights the day's date
Displaydaylist (Curdate.getfullyear (), Curdate.getmonth () +1, "dayslist");
});

An interface that sets the style externally.
Format: ([2007,10,12], "color: #f00") ([[[2007,10,20],[2007,11,25]], "COLOR: #00f")
If the month is less than 10 don't take 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<datearr.length;i++) Setdatestyle (Datearr[i],style);
}
var datastr=datearr.join (' | ');
Styledata.push (DATASTR);
Datastyle[datastr]=style;
Return
}
}
External interface
return {Setdatestyle:setdatestyle}
})();
Test style settings
Logdatecontrol.setdatestyle ([[2007,12,15],[2007,11,12]], "test");

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <ptml xmlns=" http://www.w3.org/1999/xhtml "> <pead> <title> New Document </title> &L T;meta name= "generator" content= "EditPlus"/> <meta name= "author" content= ""/> <meta name= "keywords" co Ntent= ""/> <meta name= "description" content= ""/> <style type= "Text/css" > *{font-size:14px} /* Date Outermost/#logCalendar {width:950px;border-top:1px solid #ccc border-left:1px Solid #ccc}/* All cells inside the date * * * #lo Gcalendar td{border-right:1px solid #ccc; border-bottom:1px solid #ccc; Padding-left:5px;text-align:center; height:22px;line-height:22px; } #daysList {border-top:1px solid #ccc solid #ccc}/* All cells in the date list/* * #daysList Td{text-align:cen TER;HEIGHT:22PX}/* The week and week of the input box/. Bd{border:0;text-align:center;color: #00f}//date defaultStyle */unselectday{color: #00f; font-weight:normal; Padding:3px;cursor:pointer; Text-decoration:underline}/* The date style currently clicked/* Selectday{color: #fff; Font-weight:bold;background: #FEB0B0;p adding : 1px;text-decoration:none;cursor:normal}/* Weekend style/Weekend{color: #f00} test{color: #f00; text-decoration:no NE} </style> <script type= "text/javascript" >//2007-12-21 Log Date Component Yanwei//Use closures to hide all variables and functions to prevent conflicts with outside Var Logdatecontrol= (function () {var curselel; The currently selected date Var styledata=[],datastyle={}; Gets the element var $=function (ID) {return document.getElementById (ID)} of the specified ID to calculate the number of weeks (default current date) for the specified date, which is more closely accurate VAR CA Lweek=function (DT) {var calday=dt| | New Date (); The current time to calculate var firstday=new date (calday.getfullyear (), 0, 1); The first day of the year//The calculation is currently the day of the year, 00:00 for the start of the date Var Daysall=math.floor ((calday-firstday)/1000/60/60/24) +1; Week of the first day of the year Var firstdayweekday=firstdAy.getday (); The results were added to the first week of Monday, facilitating the calculation of Var diffday=firstdayweekday==0?6:firstdayweekday-1; Daysall=daysall+diffday; Return Math.ceil (DAYSALL/7); Returns the calculated result}//Calculate one months how many days, the year 4 digits, the month 1-2 digits (should be JS date format such as January incoming 0), the data illegally 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,3 0,31]//Exists February 29 if (Month==1&&new Date (year,1,29). getmonth () ==1) {monthdays[1]=29} return Monthdays[month]}//Displays a list of dates, passing in the year, month, by daily month. such as February incoming 2), and display position var displaydaylist=function (year,month,pos) {var dayslist=[]; var cells1=$ (POS). Rows[0].cells; var cells2=$ (POS). Rows[1].cells; var daysarr=[' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' six ']; The following month-1 is converted to the JS month representation for (Var I=1,l=getdayslen (year,--Month) +1;i<l;i++) {var wd=new Date (Year,mon th,i). Getday ();Cells1[i-1].classname= ""; if (wd==0| | wd==6) {cells1[i-1].classname= "Weekend";} Add special styles for weekends//_oldcls Save the default style for 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 custom style var dtstr=year+ "|" + (month+1) + "|" +i; if (("," +styledata.join (', ') + ","). IndexOf ("," +dtstr+ ",") >-1) {cells2[i-1].classname= "Unselectday" +data STYLE[DTSTR]; Cells2[i-1].setattribute ("_oldcls", "Unselectday" +datastyle[dtstr)); //If is the current month, select the day if (new Date (). GetMonth () ==month) {curselel=cells2[new date (). Get Date ()-1]; Curselel.classname= "Selectday"; for (Var j=i-1;j<31;j++) {cells1[j].classname=cells2[j].classname= "; CELLS1[J].INNERHTML=CELLS2[J].Innerhtml= "  "; } $ (POS). Onclick=function () {changeinfo ()}//Adjust the week and week according to the selected value, you can directly pass in the DOM element that holds the date content, or the function may judge the V by the click Position. Ar 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) return; If it's not a date//The style of the selected date before recovery is curselel {curselel.classname=curselel.getattribute ("_oldcls")} C Urselel=el; Saves the currently processed element//update the selected date style 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 ()]; Days of the Week $ ("Week"). Value=calweek (DT); Number of weeks}//Initialize Window.attachevent ("onload", function () {var curdate=new Date (), CURYEAR=CURDATE.GETFU Llyear (); Displays up to ten years for (Var i=-10;i<10;i++) {$ (' year '). Add (New OptiOn (Curyear+i,curyear+i)} $ (' year '). selectedindex=10; The current year $ ("month") is selected by default. Selectedindex=curdate.getmonth (); Current Month $ ("Day"). Value=curdate.getdate (); Current Date $ ("weekday"). value=[' Day ', ' one ', ' two ', ' three ', ' four ', ' five ', ' Six '][curdate.getday ()]; Current day of the Week $ ("Week"). Value=calweek (); Current Week//change date or Year update date list $ (' year '). onchange=$ ("month"). Onchange=function () {displaydaylist ($ ("year"). Value , $ ("month"). Value, "Dayslist")}; Displays a list of the month's dates and highlights the day's date displaydaylist (Curdate.getfullyear (), Curdate.getmonth () +1, "dayslist"); }); An interface that sets the style externally. Format: ([2007,10,12], "color: #f00") ([[[2007,10,20],[2007,11,25]], "COLOR: #00f")//If the month is less than 10 don't take 0 var setdatestyle=func tion (datearr,style) {if (typeof datearr!= "Object") return; if (Datearr instanceof array) {if (datearr[0) instanceof Array) {for (Var I=0;i<datearr.leng th;i++) Setdatestyle (Datearr[i],style); } 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"); </script> </pead> <body> <table cellpadding= "3" cellspacing= "0" id= "Logcalendar" > ;tr> <td> <input type= "text" name= "Week" class= "BD" readonly size= "2" > Week </td> &LT;TD > Week <input type= "text" name= "weekday" class= "BD" readonly size= "2" ></td> <td rowspan= "2" > <table width= "100%" cellpadding= "3" height= "100%" cellspacing= "0" id= "dayslist" > <tr& Gt <td></td><td></td><td></td><td></td><td></td> <td></td><td></td><td></td><Td></td><td></td> <td></td><td></td><td></td&gt ;<td></td><td></td> <td></td><td></td><td></ Td><td></td><td></td> <td></td><td></td><td> </td><td></td><td></td> <td></td><td></td><t D></td><td></td><td></td><td></td> </tr> <tr> &LT;TD&GT;&LT;/TD&GT;&LT;TD&GT;&LT;/TD&GT;&LT;TD&GT;&LT;/TD&GT;&LT;TD&GT;&LT;/TD&GT;&L T;td></td> <td></td><td></td><td></td><td></td& Gt;<td></td> <td></td><td></td><td></td><td>&lt ;/td><td></tD> <td></td><td></td><td></td><td></td><td>& Lt;/td> &LT;TD&GT;&LT;/TD&GT;&LT;TD&GT;&LT;/TD&GT;&LT;TD&GT;&LT;/TD&GT;&LT;TD&GT;&LT;/TD&GT;&LT;TD ></td> <td></td><td></td><td></td><td></td>& lt;td></td><td></td> </tr> </table> </td> </tr> <tr> <td><select name= "Year" id= "annual" ></select> years <select name= "mo Nth "id=" month "> <option value=" 1 ">1</option> <option value=" 2 ">2</option> <o Ption value= "3" >3</option> <option value= "4" >4</option> <option value= "5" >5</optio N> <option value= "6" >6</option> <option value= "7" >7</option> <option value= "8 ">8</option> <option value= "9" >9</option> <option value= "Ten" >10</option> <option value= "one" > 11</option> <option value= "a" >12</option> </select> month </td> <td> Date < Input type= "text" Name= "Day" size= "2" class= "BD" id= "Day" ></td> </tr> </table> </body&gt ; </ptml>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.