English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Js에서 현재 날짜와 시간을 가져오고 포맷하는 코드

本文为大家分享了Js获取当前日期时间及格式化操作,具体内容如下

var myDate = new Date();
myDate.getYear();    //현재 연도 가져오기(2위치)
myDate.getFullYear();  //전체 연도 가져오기(4위치,1970-????)
myDate.getMonth();    //현재 월(0-11,0은1월)
myDate.getDate();    //현재 일(1-31)
myDate.getDay();     //현재 요일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();   //현재 시간 가져오기
myDate.toLocaleString( );    //날짜와 시간 가져오기

날짜와 시간 스크립트 라이브러리 메서드 목록
Date.prototype.isLeapYear 점 연도�断
Date.prototype.Format 날짜 포맷화
Date.prototype.DateAdd 날짜 계산
Date.prototype.DateDiff 날짜 차이 비교
Date.prototype.toString 날짜를 문자열로 변환
Date.prototype.toArray 날짜를 배열로 분할
Date.prototype.DatePart 날짜의 부분 정보 추출
Date.prototype.MaxDayOfDate 날짜가 해당 월의 가장 큰 날짜
Date.prototype.WeekNumOfYear 날짜가 해당 연도의 몇 번째 주인지 확인
StringToDate 문자열을 날짜 형식으로 변환
IsValidDate 날짜 유효성 확인
CheckDateTime 완전한 날짜와 시간 확인
datesBetween 날짜 일수 차이 

js 코드:

//--------------------------------------------------- 
// 점 연도�断 
//--------------------------------------------------- 
Date.prototype.isLeapYear = function()  
{  
  return (0==this.getYear()%)4&&((this.getYear()%100!=0)||(this.getYear()%400==0)));  
}  
//--------------------------------------------------- 
// 날짜 포맷 
// 형식 YYYY/yyyy/YY/yy 연도를 나타냅니다 
// MM/M 월 
// W/w 주 
// dd/DD/d/D 날짜 
// hh/HH/h/H 시간 
// mm/m 분 
// ss/SS/s/S 초 
//--------------------------------------------------- 
Date.prototype.Format = function(formatStr)  
{  
  var str = formatStr;  
  var Week = ['日','一','二','三','四','五','六']; 
  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' +   
  str=str.replace(/s|S/g,this.getSeconds());  
  return str;  
}  
//+--------------------------------------------------- 
//두 개의 날짜의 일 수 차이를 구합니다. 날짜 형식은 YYYY입니다-MM-dd  
//+--------------------------------------------------- 
function daysBetween(DateOne, DateTwo) 
{  
  var OneMonth = DateOne.substring5,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); 
  var 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 * Number)); 
    case 'n' :return new Date(Date.parse(dtTmp) + (60000 * Number)); 
    case 'h' :return new Date(Date.parse(dtTmp) + (3600000 * Number)); 
    case 'd' :return new Date(Date.parse(dtTmp) + (86400000 * Number)); 
    case 'w' :return 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()) + Number, 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' :return parseInt((dtEnd - dtStart) / 1000); 
    case 'n' :return parseInt((dtEnd - dtStart) / 60000); 
    case 'h' :return parseInt((dtEnd - dtStart) / 3600000); 
    case 'd' :return parseInt((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 = ['日','一','二','三','四','五','六']; 
    str += ' 월요일' + Week[myDate.getDay()]; 
  } 
  return str; 
} 
//+--------------------------------------------------- 
//| 날짜 유효성 검증 
//| 형식: YYYY-MM-DD 또는 YYYY/MM/DD 
//+--------------------------------------------------- 
  
{  
  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-  
  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-  
  {  
    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. 윤년 주의하세요.');  
    return false;  
  }  
  return 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 })$/month = month  
  var r = str.match(reg);  
  if(r==null)return false;  
  r[2]=r[2];-1month = month  
  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(); 
  myArray[2] = myDate.getDate(); 
  myArray[3] = myDate.getHours(); 
  myArray[4] = myDate.getMinutes(); 
  myArray[5] = myDate.getSeconds(); 
  return myArray; 
} 
//+--------------------------------------------------- 
//| 날짜 데이터 정보를 얻습니다 
//| 매개변수 interval은 데이터 유형을 나타냅니다 
//| y 년 m월 d일 w요일 ww 주 h시 n분 s초 
//+--------------------------------------------------- 
Date.prototype.DatePart = function(interval) 
{  
  var myDate = this; 
  var partStr=''; 
  var Week = ['日','一','二','三','四','五','六']; 
  switch (interval) 
  {  
    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; 
    case 'h' :partStr = myDate.getHours();break; 
    case 'n' :partStr = myDate.getMinutes();break; 
    case 's' :partStr = myDate.getSeconds();break; 
  } 
  return partStr; 
} 
//+--------------------------------------------------- 
//| 현재 날짜가 속한 월의 가장 많은 날 수를 얻습니다 
//+--------------------------------------------------- 
Date.prototype.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 
  return result; 
} 
//+--------------------------------------------------- 
//| 현재 날짜가 연도의 몇 번째 주인지 확인 
//+--------------------------------------------------- 
Date.prototype.WeekNumOfYear = function() 
{  
  var myDate = this; 
  var ary = myDate.toArray(); 
  var year = ary[0]; 
  var month = ary[1];+1month = month 
  var day = ary[2]; 
  document.write('< script language=VBScript\> \n'); 
  document.write('myDate = Datue('+month+'-'+day+'-'+year+'') \n'); 
  document.write('result = DatePart('ww', myDate) \n'); 
  document.write(' \n'); 
  return result; 
} 
//+--------------------------------------------------- 
//| 문자열을 날짜 형식으로 변환  
//| 포맷 MM/dd/YYYY 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]); 
  } 
  return myDate; 
} 

이와 같은 시계를 구현하려면:
2012년12월03일 17:21:16 월요일

 //로컬 시계
function clockon() {
  var now = new Date();
  var year = now.getFullYear(); //getFullYear getYear
  var month = now.getMonth();
  var date = now.getDate();
  var day = now.getDay();
  var day = now.getDay();
  var hour = now.getHours();
  var minu = now.getMinutes();
  var sec = now.getSeconds();
  var week; + 1month = month
  ; 10) month = "0" + month;
  if (date < 10) date = "0" + date;
  if (hour < 10) hour = "0" + hour;
  if (minu < 10) minu = "0" + minu;
  if (sec < 10) sec = "0" + sec;
  var arr_week = new Array("일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일");
  week = arr_week[day];
  var time = "";
  time = year + "년" + month + "월" + date + "일" + " " + hour + :" + minu + :" + sec + " " + week;
  $("#bgclock").html(time);
  var timer = setTimeout("clockon()", 200);
}

이以上就是 본 문서의 전체 내용입니다. 여러분의 학습에 도움이 되길 바라며, 간절히 다른 강의에도 많은 지지를 부탁드립니다.

선언: 이 문서의 내용은 인터넷에서 가져왔으며, 저작권은 원 저자에게 있으며, 인터넷 사용자가 자발적으로 기여하고 업로드한 내용입니다. 이 사이트는 소유권을 가지지 않으며, 인공적인 편집 처리를 하지 않았으며, 관련 법적 책임을 부담하지 않습니다. 저작권 침해 내용이 발견되면, notice#w로 이메일을 보내 주세요.3codebox.com에 이메일을 보내시면, #을 @으로 바꿔서 신고하시고 관련 증거를 제공해 주세요. 확인되면, 이 사이트는 즉시 저작권 침해 내용을 제거합니다.

추천해 드립니다