JavaScript는 현재 날짜와 시간 및 기타 작업 함수를 가져옵니다._시간 및 날짜

WBOY
풀어 주다: 2016-05-16 18:12:14
원래의
731명이 탐색했습니다.

myDate.getYear(); //현재 연도(2자리) 가져오기
myDate.getFullYear() //전체 연도 가져오기(4자리, 1970-????)
myDate.getMonth() ; //현재 월 가져오기(0-11, 0은 1월을 나타냄)
myDate.getDate(); //현재 날짜 가져오기(1-31)
myDate.getDay(); week X( 0-6, 0은 일요일을 나타냄)
myDate.getTime(); //현재 시간을 가져옵니다(1970.1.1 이후의 밀리초 수)
myDate.getHours() //현재 시간을 가져옵니다. 시간(0~23)
myDate.getMinutes(); //현재 분 가져오기(0~59)
myDate.getSeconds() //현재 초 가져오기(0~59)
myDate.getMilliseconds() ; //현재 밀리초 가져오기(0-999)
myDate.toLocaleDateString(); //현재 날짜 가져오기
var mytime=myDate.toLocaleTimeString(); time
myDate.toLocaleString( ; .DateAdd 날짜 계산
Date.prototype.DateDiff 날짜 차이 비교
Date.prototype.toString 날짜를 문자열로 변환
Date.prototype.toArray 날짜를 배열로 분할
Date.prototype.DatePart 날짜 가져오기 부분 정보
Date.prototype.MaxDayOfDate 날짜가 있는 달의 최대 일 수를 가져옵니다.
Date.prototype.WeekNumOfYear 날짜가 있는 연도의 주를 결정합니다. located
StringToDate 문자열을 날짜 유형으로 변환
IsValidDate 날짜 유효성 확인
CheckDateTime 날짜 및 시간 확인 완료
daysBetween 날짜-일 차이




복사 코드

코드는 다음과 같습니다.

//-------------------------------------------- ------ ----------
// 윤년 결정
//--------- ----------- ----------
Date.prototype.isLeapYear = function()
{
return (0==this.getYear( )%4&&((this.getYear() 0!=0)||(this.getYear()@0==0)))
}

//------ -------------------------- --------
/ / 날짜 형식
// 형식 YYYY/yyyy/YY/yy는 연도를 나타냅니다
// MM/M월
//주/주
// dd/DD/d/D 날짜
// hh/HH/h/H 시간
// mm/m 분
// ss/SS/s/S 초
/ /------------ -------------------------- -
Date.prototype.Format = function(formatStr)
{
var str = formatStr
var Week = ['日','一','two','三',' 4','五','六' ];

str=str.replace(/yyyy|YYYY/,this.getFullYear())
str=str.replace(/yy|YY /,(this.getYear() % 100 )>9?(this.getYear() % 100).toString():'0' (this.getYear() % 100))

str =str.replace(/MM/,this .getMonth()>9?this.getMonth().toString():'0' this.getMonth())
str=str.replace(/M/ g,this.getMonth());

str=str.replace(/w|W/g,Week[this.getDay()])

str=str.replace( /dd|DD/,this.getDate( )>9?this.getDate().toString():'0' this.getDate())
str=str.replace(/d|D/g ,this.getDate());

str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' this. getHours());
str= str.replace(/h|H/g,this.getHours())
str=str.replace(/mm/,this.getMinutes()>9? this.getMinutes().toString(): '0' this.getMinutes());
str=str.replace(/m/g,this.getMinutes())

str=str .replace(/ss|SS/,this .getSeconds()>9?this.getSeconds().toString():'0' this.getSeconds())
str=str.replace(/s| S/g,this.getSeconds()) ;

return str
}

// ------------------ ---------- ----------
//| 두 날짜 사이의 날짜 차이를 구합니다. 형식은 YYYY-MM-dd
// - ------------------------ -------------
function daysBetween(DateOne,DateTwo)
{
var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'))
var OneDay = DateOne.substring(DateOne.length, DateOne.lastIndexOf ('-') 1)
var OneYear = DateOne.substring(0,DateOne.indexOf ('-'))

var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('-'))
var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('-') 1); TwoYear = DateTwo.substring(0,DateTwo.indexOf (' -'))

var cha=((Date.parse(OneMonth '/' OneDay '/' OneYear)- Date.parse(TwoMonth ' /' TwoDay '/' TwoYear))/86400000)
return Math.abs(cha)
}


// ----------- --------------- ----------------
//| 날짜 계산
// ---------- --------------------------------- ---------
Date.prototype.DateAdd = function(strInterval, Number) {
var dtTmp = this
switch(strInterval) {
case 's' :return new Date(Date.parse(dtTmp) (1000 * 숫자));
case 'n' :return new Date(Date.parse(dtTmp) (60000 * 숫자))
case 'h' :return new Date(Date.parse(dtTmp) (3600000 * 숫자));
case 'd' :return new Date(Date.parse(dtTmp) (86400000 * 숫자)); new Date(Date.parse(dtTmp) ((86400000 * 7) * Number) );
case 'q' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) Number*3, dtTmp .getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp .getSeconds())
case 'm' :return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) 숫자 , dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes() , dtTmp.getSeconds())
case 'y' :return new Date((dtTmp.getFullYear() Number), dtTmp.getMonth (), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes (), dtTmp.getSeconds())
}
}

// ------ ------- ----------------
//| 날짜 차이 비교 dtEnd 형식은 날짜 유형이거나 유효한 날짜 형식 문자열입니다.
//--------------- -------- ---
Date.prototype.DateDiff = function(strInterval, dtEnd) {
var dtStart = this; >if (typeof dtEnd == 'string' )//문자열인 경우 날짜 유형으로 변환
{
dtEnd = StringToDate(dtEnd)
}
switch (strInterval) {
case 's' :returnparseInt((dtEnd - dtStart) / 1000)
case 'n' :returnparseInt((dtEnd - dtStart) / 60000)
case 'h' :returnparseInt ((dtEnd - dtStart) / 3600000);
case 'd' :return parsInt((dtEnd - dtStart) / 86400000)
case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));
case 'm' :return (dtEnd.getMonth() 1) ((dtEnd .getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth() 1); >case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear()
}
}

//-------------------------------------------- --- ---------
//| 날짜 출력 문자열, 시스템의 toString 메서드가 오버로드됨
// ----- ----------------------------------
Date.prototype.toString = function(showWeek)
{
var myDate= this
var str = myDate.toLocaleDateString()
if (showWeek)
{
var Week = ['일','월요일','2' , '3','4','5','6'];
str = '주' 주[myDate.getDay()]
}
return str; 🎜 >
// ------------------------------ ---- -------
//| 날짜 적법성 확인
//| 형식은 YYYY-MM-DD 또는 YYYY/MM/DD
// ---- ---- -------------------
function IsValidDate(DateStr )
{
var sDate=DateStr.replace(/(^s |s $)/g,'') //양쪽 공백 제거
if(sDate; =='') return true;
//형식이 YYYY-(/)MM-(/)DD 또는 YYYY-(/)M-(/)DD 또는 YYYY-(/)M-(/를 충족하는 경우 )D 또는 YYYY-(/)MM -(/)D는 ''로 대체됩니다.
//데이터베이스에서 법적 날짜는 YYYY-MM/DD(2003-3/21)일 수 있으며 데이터베이스는 YYYY-MM-DD 형식으로 자동 변환
var s = sDate.replace(/[d]{ 4,4 }[-/]{ 1 }[d]{ 1,2 }[-/]{ 1 } [d]{ 1,2 }/g,' ');
if (s=='') //설명 형식은 YYYY-MM-DD 또는 YYYY-M-DD 또는 YYYY-M-D 또는 YYYY-를 충족합니다. MM-D
{
var t= new Date(sDate.replace(/-/g,'/'))
var ar = sDate.split(/[-/:]/);
if(ar[0] != t.getYear() || ar[1] != t.getMonth() 1 || ar[2] != t.getDate())
{
//alert('날짜 형식이 잘못되었습니다! 형식은 YYYY-MM-DD 또는 YYYY/MM/DD입니다. 윤년에 주의하세요. ');
return false;
}
}
else
{
//alert('날짜 형식이 잘못되었습니다. 형식은 YYYY-MM-DD 또는 YYYY/MM입니다. /DD. 윤년을 참고하세요.');
false 반환
}
true 반환
}

// ------------------ ------------------
//| 날짜 및 시간 확인
//| : YYYY-MM-DD HH:MM:SS
// ---------------------------------- ----------------
function CheckDateTime(str)
{
var reg = /^(d )-(d{ 1,2 })-( d{ 1,2 }) (d{ 1,2 }):(d{ 1,2 }):(d{ 1,2 })$/
var r = str.match(reg); 🎜>if(r==null)return false
r[2]=r[2]-1
var d= new Date(r[1],r[2],r[3] ,r[4],r[5],r[6]);
if(d.getFullYear()!=r[1])return false
if(d.getMonth()!=r; [2])return false;
if(d.getDate()!=r[3])return false
if(d.getHours()!=r[4])return false; if(d.getMinutes()!=r[5])return false;
if(d.getSeconds()!=r[6])return false
return true;
//---------------------------------- --- ------
//| 날짜를 배열로 분할
// ------------ --- ----------
Date.prototype.toArray = function()
{
var myDate = this;
var myArray = Array();
myArray[0] = myDate.getFullYear();
myArray[1] = myDate.getMonth()
myDate.getDate( );
myArray[3] = myDate.getHours();
myArray[4] = myDate.getMinutes();
myArray[5] = myDate.getSeconds();
}

// ------------------------- ---- ----------
//| 날짜 데이터 정보 가져오기
//| 매개변수 간격은 데이터 유형을 나타냅니다.
//| 주 ww 주 h 시간 n 분 초
//-------------------------------------- --------- ---------
Date.prototype.DatePart = 함수(간격)
{
var myDate = this
var partStr=' ';
var Week = [ '일','일','이','삼','사','오','六']
전환(간격)
{
case 'y' :partStr = myDate.getFullYear();break;
case 'm' :partStr = myDate.getMonth() 1;break
case 'd' :partStr = myDate.getDate( );break;
case 'w' :partStr = Week[myDate.getDay()];break
case 'ww' :partStr = myDate.WeekNumOfYear();break; :partStr = myDate.getHours();
case 'n' :partStr = myDate.getMinutes();break
case 's' :partStr = myDate.getSeconds();break; }
partStr 반환
}

// ------------------ --------- ----------
//| 현재 날짜의 월 최대 일수를 가져옵니다.
// ------- ------------- ------------------
날짜.프로토타입 .MaxDayOfDate = function()
{
var myDate = this;
var ary = myDate.toArray()
var date1 = (new Date(ary[0],ary[1] 1 ,1));
var date2 = date1.dateAdd(1,'m',1);
var result = dateDiff(date1.Format('yyyy-MM-dd'),date2.Format(' yyyy-MM-dd'));
결과 반환
}

// ----------------------- ---- ---------------
//| 현재 날짜가 속한 연도의 주를 가져옵니다.
// ---------- ---------------------- -----
Date.prototype.WeekNumOfYear = function ()
{
var myDate = this
var ary = myDate.toArray()
var year = ary[0 ];
var 월 = ary[1] 1;
var day = ary[2]
document.write('< 스크립트 언어=VBScript> n'); ('myDate = DateValue('' 월 '-' 일'- ' 연도 '') n');
document.write('result = DatePart('ww', myDate) n'); .write('n');
결과 반환
}

// ----------- --------------- ------------
//| 문자열을 날짜 유형으로 변환
//| MM-dd-YYYY YYYY/MM/dd YYYY-MM- dd
// ----------------- ---- -------
function StringToDate(DateStr)
{

var Converted = Date.parse(DateStr );
var myDate = new Date(converted);
if (isNaN(myDate))
{
//var delimCahar = DateStr.indexOf('/')!=-1?' /':'-';
var arys= DateStr.split( '-');
myDate = new Date(arys[0],--arys[1],arys[2]); >}
myDate 반환
}

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!