컴퓨터 Javascript 문자열을 포맷 맞춰 날짜로, 날짜를 포맷 맞춘 문자열로 변환
2020.11.26 00:57
String.toDate() 는 문자열을 지정한 포맷대로 인식해 Date 객체 반환
Date.format() 은 Date 객체를 지정된 포맷대로 문자열로 변환
/**
* @type : prototype_function
* @access : public
* @desc : 자바스크립트의 내장 객체인 String 객체에 toDate 메소드를 추가한다. toDate 메소드는 날짜를 표현하는
* 스트링 값을 자바스크립트의 내장 객체인 Date 객체로 변환한다.
* <pre>
* var date = "20020305".toDate();
* or
* var date = "20020305".toDate("YYYYMMDD");
* or
* var date = "2002.03.05".toDate("YYYY.MM.DD");
* </pre>
* 위의 예에서 date 변수는 실제로 2002년 3월 5일을 표현하는 Date 오브젝트를 가르킨다.
* @sig : [pattern]
* @param : pattern optional Date를 표현하고 있는 현재의 String을 pattern으로 표현한다. (default : YYYYMMDD)
* <pre>
* # syntex
*
* YYYY : year(4자리)
* YY : year(2자리)
* MM : month in year(number)
* DD : day in month
* HH : hour in day (0~23)
* mm : minute in hour
* ss : second in minute
* SS : millisecond in second
*
* <font color=red>주의)</font> YYYY(YY)는 반드시 있어야 한다. YYYY(YY) 만 사용할 경우는 1월 1일을 기준으로
* 하고 YYYY와 MM 만사용할 경우는 1일을 기준으로 한다.
* </pre>
* @return : 변환된 Date Object.
* @author :
*/
String.prototype.toDate = function(pattern) {
var index = -1;
var year;
var month;
var day;
var hour = 0;
var min = 0;
var sec = 0;
var ms = 0;
var newDate;
// 값이 없거나 맞지 않을 경우 UTC 1970-01-01 로 Date 객체를 만들어 return 한다.
// 아래 Date.prototype.format 이 오류를 발생시키지 않도록 하기 위해서이며, format 에서 UTC 1970-01-01 이면 빈 문자열을 return 함.
var nullDate = new Date(0);
if(fnIsNull(this))
{
return nullDate;
}
// 입력된 패턴이 없을 경우 데이터에서 정규표현식으로 직접 체크
if (fnIsNull(pattern)) {
var checkPattern = /^(19|20)*(\d{2})[\.\-\/]*(\d{2})[\.\-\/]*(\d{2})([\s\.\-\/\:]*(\d{2})[\.\-\/\:]*(\d{2})[\.\-\/\:]*(\d{2})[\.\-\/\:]*(\d{2})*)*$/;
var dateArray = checkPattern.exec(this);
// 정규표현식 패턴과 매칭됐을 경우 정규식 결과에 따라 날짜 생성
if(!fnIsNull(dateArray))
{
// 1900년대/2000년대를 뜻하는 19/20 으로 시작되지 않았을 경우 70년 미만일경우 2000년대로, 70 이상이면 1900년대로
if(fnIsNull(dateArray[1]))
{
if(parseInt(dateArray[2]) < 70)
{
year = "20" + dateArray[2];
}
else
{
year = "19" + dateArray[2];
}
} // End of if(fnIsNull(dateArray[1]))
// 19/20으로 시작되면 그대로 결합
else
{
year = dateArray[1] + dateArray[2];
}
// 연도가 만들어진 후 날짜 검사 해서 문제가 있으면 1970-01-01로 설정
if(!fnIsValidDate(year + dateArray[3] + dateArray[4]))
{
newDate = nullDate;
}
// 정상이면 날짜 생성
else
{
// 날짜 생성
newDate = new Date(year, parseInt(dateArray[3]) - 1, dateArray[4], NVL(dateArray[6], 0), NVL(dateArray[7], 0), NVL(dateArray[8], 0), NVL(dateArray[9], 0));
}
} // End of if(!fnIsNull(dateArray))
// 정규표현식에 매칭되지 않았을 경우 1970-01-01 로 설정
else
{
newDate = nullDate;
} // End of else
return newDate;
}
else
{
if ((index = pattern.indexOf("YYYY")) == -1 ) {
index = pattern.indexOf("YY");
if(parseInt(this.substr(index, 2)) < 70)
{
year = "20" + this.substr(index, 2);
}
else
{
year = "19" + this.substr(index, 2);
}
} else {
year = this.substr(index, 4);
}
if ((index = pattern.indexOf("MM")) != -1 ) {
month = this.substr(index, 2);
} else {
month = 1;
}
if ((index = pattern.indexOf("DD")) != -1 ) {
day = this.substr(index, 2);
} else {
day = 1;
}
if ((index = pattern.indexOf("HH")) != -1 ) {
hour = this.substr(index, 2);
}
if ((index = pattern.indexOf("mm")) != -1 ) {
min = this.substr(index, 2);
}
if ((index = pattern.indexOf("ss")) != -1 ) {
sec = this.substr(index, 2);
}
if ((index = pattern.indexOf("SS")) != -1 ) {
ms = this.substr(index, 2);
}
newDate = new Date(year, month - 1, day, hour, min, sec, ms);
}
if (month > 12) {
newDate.setFullYear(year + 1);
} else {
newDate.setFullYear(year);
}
return newDate;
};
/**
* @type : prototype_function
* @object : Date
* @access : public
* @desc : 자바스크립트의 내장 객체인 Date 객체에 format 메소드를 추가한다. format 메소드는 Date 객체가 가진 날짜를
* 지정된 포멧의 스트링으로 변환한다.
* <pre>
* var dateStr = new Date().format("YYYYMMDD");
*
* 참고 : Date 오브젝트 생성자들 - dateObj = new Date()
* - dateObj = new Date(dateVal)
* - dateObj = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]])
* </pre>
* 위의 예에서 오늘날짜가 2002년 3월 5일이라면 dateStr의 값은 "20020305"가 된다.
* default pattern은 "YYYYMMDD"이다.
* @sig : [pattern]
* @param : pattern optional 변환하고자 하는 패턴 스트링. (default : YYYYMMDD)
* <pre>
* # syntex
*
* YYYY : full year (e.g.: 2018, 2019, 2020...)
* YY : year (18, 19, 20...)
* MM : month in year (01, 02, 03... ~ 12)
* mn : month in year (1, 2, 3... ~ 12)
* MON : month in year e.g.) 1월(January)
* MN : short month in year e.g.) Jan
* DD : day in month (01, 02, 03... ~ 31)
* dd : day in month (1, 2, 3... ~ 31)
* DAY : day in week 예) "일요일(Sunday)"
* DY : short day in week 예) "일(Sun)"
* hh : hour in am/pm (01, 02, 03... ~ 12)
* h : hour in am/pm (1, 2, 3... ~ 12)
* HH : hour in day (00, 01, 02... ~23)
* H : hour in day (0, 1, 2...~23)
* mm : minute in hour (00, 01, 02... ~ 59)
* m : minute in hour (0, 1, 2... ~ 59)
* ss : second in minute (00, 01, 02... ~ 59)
* s : second in minute (0, 1, 2... ~ 59)
* SS : millisecond in second
* a : "오전(AM)/오후(PM) 구분"
* A : "언어 관계없이 무조건 AM/PM 으로 표시"
* </pre>
* @return : Date를 표현하는 변환된 String.
*/
Date.prototype.format = function(pattern, lang) {
// Null 이거나 Date 객체의 시간이 1970-01-01 일 경우 빈 값을 Return 한다.
// String 이 toDate 를 썼는데 빈 값이거나 맞지 않을 때 이 값으로 들어옴.
if(fnIsNull(this) || this.getTime() == 0)
{
return "";
}
if(!fnIsNull(lang) && lang == "en")
{
var MONTH_IN_YEAR = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var DAY_SHORT_IN_WEEK = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
var DAY_LONG_IN_WEEK = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
var AM_PM = new Array("AM", "PM");
}
else
{
var MONTH_IN_YEAR = new Array("1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월");
var DAY_SHORT_IN_WEEK = new Array("일", "월", "화", "수", "목", "금", "토");
var DAY_LONG_IN_WEEK = new Array("일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일");
var AM_PM = new Array("오전", "오후");
}
var MONTH_LONG_IN_YEAR = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var year = this.getFullYear();
var month = this.getMonth() + 1;
var day = this.getDate();
var dayInWeek = this.getDay();
var hour24 = this.getHours();
var hour12 = (hour24 > 12) ? (hour24 - 12) : hour24;
var AMPM = (hour24 > 11) ? AM_PM[1] : AM_PM[0];
var GLB_AMPM = (hour24 > 11) ? "PM" : "AM";
var min = this.getMinutes();
var sec = this.getSeconds();
var YYYY = "" + year;
var YY = YYYY.substr(2);
var MM = month.appendZero();
var mn = month;
var MON = MONTH_IN_YEAR[month-1];
var MN = MONTH_LONG_IN_YEAR[month-1];
var DD = day.appendZero();
var dd = day;
var DAY = DAY_LONG_IN_WEEK[dayInWeek];
var DY = DAY_SHORT_IN_WEEK[dayInWeek];
var HH = hour24.appendZero();
var H = hour24;
var hh = hour12.appendZero();
var h = hour12;
var mm = min.appendZero();
var m = min;
var ss = sec.appendZero();
var s = sec;
var dateStr;
if (fnIsNull(pattern))
{
dateStr = "YYYYMMDD";
}
else
{
dateStr = pattern;
}
if(dateStr.indexOf("A") > -1)
{
dateStr = dateStr.replace(/A/g, GLB_AMPM);
}
if(dateStr.indexOf("a") > -1)
{
dateStr = dateStr.replace(/a/g, AMPM);
}
dateStr = dateStr.replace(/YYYY/g, YYYY);
dateStr = dateStr.replace(/YY/g, YY);
dateStr = dateStr.replace(/MM/g, MM);
dateStr = dateStr.replace(/mn/g, mn);
dateStr = dateStr.replace(/DD/g, DD);
dateStr = dateStr.replace(/dd/g, dd);
dateStr = dateStr.replace(/hh/g, hh);
dateStr = dateStr.replace(/HH/g, HH);
dateStr = dateStr.replace(/mm/g, mm);
dateStr = dateStr.replace(/ss/g, ss);
dateStr = dateStr.replace(/h/g, h);
dateStr = dateStr.replace(/m/g, m);
dateStr = dateStr.replace(/s/g, s);
dateStr = dateStr.replace(/MON/g, MON);
dateStr = dateStr.replace(/MN/g, MN);
dateStr = dateStr.replace(/DY/g, DY);
dateStr = dateStr.replace(/DAY/g, DAY);
return dateStr;
};






