티스토리 뷰

🌈 JavaScript

날짜와 관련된 함수

James Wetzel 2024. 4. 1. 10:17

Date.now() 메소드는

UTC 기준으로 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 밀리초를 반환합니다.

console.log(Date.now());
// 1711935339429

 

 

Date.toDateString() 메소드는

주어진 날짜를 현지 시간대로 해석하고 그 중 날짜 부분만 표시하는 문자열을 반환합니다.

const currentDateOnly = new Date().toDateString();
console.log(currentDateOnly);
// "Mon Apr 01 2024"

 

 

Date.toLocaleDateString() 메소드는

지역화된 날짜 정보를 문자열로 반환합니다.

const currentDate = new Date().toLocaleString();
console.log(currentDate);
// "2024. 4. 1. 오전 10:44:23"

 

 

Date Constructor(생성자)는

시간의 특정 지점을 나타내는 Date 객체를 플랫폼에 종속되지 않는 형태로 생성합니다. Date 객체는 1970년 1월 1일 UTC(국제표준시) 자정으로부터 지난 시간을 밀리초로 나타내는 UNIX 타임스탬프를 담습니다.

const year = new Date().getFullYear();
const month = new Date().getMonth();
const day = new Date().getDay();
console.log(year, month, day);


const currentDateObject = new Date(year, month, day);
console.log(currentDateObject);


const options = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
};
console.log(currentDateObject.toLocaleDateString(undefined, options));
console.log(new Date().toLocaleDateString(undefined, options));

 

 

addDay() 사용자 정의 함수는 

입력 받은 숫자를 현재 날짜에 더하고, 더 해진 날짜 정보를 반환합니다.

Date.prototype.addDay = function(day){
  current_date_millisecond = Date.parse(this) + (((((day * 24) * 60 * 60)) * 1000));
  return new Date(current_date_millisecond);  
};

console.log(new Date().addDay(7));

 

 

dateDiff() 사용자 정의 함수는

입력받은 start_date 와 end_date 가 몇일 간의 간격, 일 수를 가지고 있는지에 대한 일 수를 반환합니다. 

Date.prototype.dateDiff = function(start_date, end_date){
  const start_date_millisecond = Date.parse(start_date);
  const end_date_millisecond = Date.parse(end_date);

  console.log(start_date_millisecond);
  console.log(end_date_millisecond);

  const datediff_millisecond = end_date_millisecond - start_date_millisecond
  console.log(datediff_millisecond);

  const datediff_day = (datediff_millisecond / (((1000 * 60) * 60) * 24))
  return Math.floor(datediff_day);
}

const start_date = "2024-03-25";
const end_date = "2024-04-01";

console.log(`두 날짜 간의 차이는 ${new Date().dateDiff(start_date, end_date)}일입니다.`);

 

 

 

추가 정보

서버 개발 언어의 경우

일반적으로 DateTime.Now 를 호출하게되면 현재의 날짜 정보를 가져 온다.

 

하지만

자바스크립트의 경우

Date.now() 함수를 호출하게 되면(1711937827716) 이와 같은 숫자를 반환한다.

( UTC 기준으로 1970년 1월 1일 0시 0분 0초부터 현재까지 경과된 밀리초를 반환합니다.)

 

그래서

위 예제 코드처럼 "new" 키워드를 명시적으로 사용해 줌으로써 현재의 날짜 정보를 가져 올 수 있다.

 

 

 

 

const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
const options = {
  weekday: 'long',
  year: 'numeric',
  month: 'long',
  day: 'numeric',
};

console.log(event.toLocaleDateString('de-DE', options));
// Expected output (varies according to local timezone): Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('ar-EG', options));
// Expected output (varies according to local timezone): الخميس، ٢٠ ديسمبر، ٢٠١٢

console.log(event.toLocaleDateString(undefined, options));
// Expected output (varies according to local timezone and default locale): Thursday, December 20, 2012

 

추가 정보

/**
* 지정날짜에 추가일을 더한 포맷 날짜 문자열을 얻는다
* 
* @param {int} addValue 추가할 날짜 수
* @param {String} addType "yy", "mm", "dd" 중 한가지를 지정하며, 각 지정에 따라 연, 월, 일을 증가시킨다
* @param {String} nDate 기준 날짜, 지정되지 않을 경우 현재 날짜를 기준으로 한다
* @return String
*/
DateUtil.DateAdd = function (addValue, addType, nDate) {
	var dt = DateUtil.ReturnDateTypeValue(nDate);

	switch (addType.toLowerCase()) {
		case "yy":
			{// year
				dt.setFullYear(dt.getFullYear() + parseInt(addValue));
				break;
			}

		case "mm":
			{// month
				dt.setMonth(dt.getMonth() + parseInt(addValue));
				break;
			}
		case "dd":
			{// day
				dt.setDate(dt.getDate() + parseInt(addValue));
				break;
			}
	}

	return DateUtil.FormatDate(dt);
};
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함