programing

JavaScript에서 현재 연도 가져오기

prostudy 2022. 10. 13. 23:28
반응형

JavaScript에서 현재 연도 가져오기

JavaScript에서 현재 연도를 얻으려면 어떻게 해야 합니까?

개체를 만들고 다음을 호출합니다.

new Date().getFullYear()  // returns the current year

사용 예: 항상 현재 연도를 표시하는 페이지 바닥글:

document.getElementById("year").innerHTML = new Date().getFullYear();
footer {
  text-align: center;
  font-family: sans-serif;
}
<footer>
    ©<span id="year"></span> by Donald Duck
</footer>

생성자의 전체 메서드 목록을 참조하십시오.

// Return today's date and time
var currentTime = new Date()

// returns the month (from 0 to 11)
var month = currentTime.getMonth() + 1

// returns the day of the month (from 1 to 31)
var day = currentTime.getDate()

// returns the year (four digits)
var year = currentTime.getFullYear()

// write output MM/dd/yyyy
document.write(month + "/" + day + "/" + year)

여기 날짜를 얻을 수 있는 다른 방법이 있습니다.

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

HTML 웹 페이지에 삽입하여 출력하는 방법은 다음과 같습니다.

<div class="container">
    <p class="text-center">Copyright &copy; 
        <script>
            var CurrentYear = new Date().getFullYear()
            document.write(CurrentYear)
        </script>
    </p>
</div>

HTML 페이지 출력은 다음과 같습니다.

저작권 © 2018

JS 코드 한 줄로 현재 연도를 얻을 수 있습니다.

<p>Copyright <script>document.write(new Date().getFullYear());</script></p>

금년도에는 Date 클래스에서 getFullYear()를 사용할 수 있지만 요건에 따라 사용할 수 있는 함수가 많습니다.일부 함수는 다음과 같습니다.

var now = new Date()
console.log("Current Time is: " + now);

// getFullYear function will give current year 
var currentYear = now.getFullYear()
console.log("Current year is: " + currentYear);

// getYear will give you the years after 1990 i.e currentYear-1990
var year = now.getYear()
console.log("Current year is: " + year);

// getMonth gives the month value but months starts from 0
// add 1 to get actual month value 
var month = now.getMonth() + 1
console.log("Current month is: " + month);

// getDate gives the date value
var day = now.getDate()
console.log("Today's day is: " + day);

javascript는 이렇게 간단하게 사용할 수 있습니다.그렇지 않으면 대규모 애플리케이션에서 도움이 되는 momentJs 플러그인을 사용할 수 있습니다.

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

function generate(type,element)
{
	var value = "";
	var date = new Date();
	switch (type) {
		case "Date":
			value = date.getDate();		// Get the day as a number (1-31)
			break;
		case "Day":
			value = date.getDay();		// Get the weekday as a number (0-6)
			break;
		case "FullYear":
			value = date.getFullYear();	// Get the four digit year (yyyy)
			break;
		case "Hours":
			value = date.getHours();	// Get the hour (0-23)
			break;
		case "Milliseconds":
			value = date.getMilliseconds();	// Get the milliseconds (0-999)
			break;
		case "Minutes":
			value = date.getMinutes();     // Get the minutes (0-59)
			break;
		case "Month":
			value = date.getMonth();	// Get the month (0-11)
			break;
		case "Seconds":
			value = date.getSeconds();	// Get the seconds (0-59)
			break;
		case "Time":
			value = date.getTime();		// Get the time (milliseconds since January 1, 1970)
			break;
	}

	$(element).siblings('span').text(value);
}
li{
  list-style-type: none;
  padding: 5px;
}

button{
  width: 150px;
}

span{
  margin-left: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<ul>
	<li>
		<button type="button" onclick="generate('Date',this)">Get Date</button>
		<span></span>
	</li>
	<li>
		<button type="button" onclick="generate('Day',this)">Get Day</button>
		<span></span>
	</li>
	<li>
		<button type="button" onclick="generate('FullYear',this)">Get Full Year</button>
		<span></span>
	</li>
	<li>
		<button type="button" onclick="generate('Hours',this)">Get Hours</button>
		<span></span>
	</li>
	<li>
		<button type="button" onclick="generate('Milliseconds',this)">Get Milliseconds</button>
		<span></span>
	</li>

	<li>
		<button type="button" onclick="generate('Minutes',this)">Get Minutes</button>
		<span></span>
	</li>
	<li>
		<button type="button" onclick="generate('Month',this)">Get Month</button>
		<span></span>
	</li>
	<li>
		<button type="button" onclick="generate('Seconds',this)">Get Seconds</button>
		<span></span>
	</li>
	<li>
		<button type="button" onclick="generate('Time',this)">Get Time</button>
		<span></span>
	</li>
</ul>

이 예를 들어, 바닥글의 스크립트를 참조하지 않고 표시할 위치에 배치할 수 있습니다.또, 다른 대답과 같은 장소에 배치할 수도 있습니다.

<script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>

예를 들어 바닥글의 저작권 참고 사항

Copyright 2010 - <script>new Date().getFullYear()>document.write(new Date().getFullYear());</script>

클래스 Date를 인스턴스화하고 getFullYear 메서드를 호출하여 yyy 형식으로 현재 연도를 가져옵니다.다음과 같은 경우:

let currentYear = new Date().getFullYear();

currentYear 변수는 사용자가 찾는 값을 유지합니다.

TL, DR

여기에 기재되어 있는 답변의 대부분은 로컬 머신의 타임 존과 오프셋(클라이언트측)에 근거해 현년이 필요한 경우에만 정답입니다.이것은, 대부분의 시나리오에서는 신뢰성이 있다고는 할 수 없습니다(머신 마다 다를 수 있기 때문입니다).

신뢰할 수 있는 출처는 다음과 같습니다.

  • 웹 서버의 시계(단, 업데이트되었는지 확인)
  • 시간 API 및 CDN

세부 사항

「 」에서 .Date으로 값을 합니다.

자세한 내용은 "MDN 웹 문서: JavaScript 날짜" 개체를 참조하십시오.

편의를 위해 관련 문서를 추가했습니다.

(...) 날짜 및 시간 또는 해당 구성요소를 가져오는 기본 방법은 모두 로컬(즉, 호스트 시스템) 시간대 및 오프셋에서 작동합니다.

를 언급하는 또 다른 소스는 JavaScript 날짜시간 객체입니다.

누군가의 시계가 몇 시간 동안 꺼져 있거나 다른 표준 시간대에 있는 경우 날짜 개체는 자신의 컴퓨터에서 생성된 시간과는 다른 시간을 만듭니다.

사용할 수 있는 신뢰할 수 있는 소스는 다음과 같습니다.

그러나 단순히 시간 정확도에 관심이 없거나 사용 사례에 로컬 머신의 시간에 비례하는 시간 값이 필요한 경우 Javascript를 안전하게 사용할 수 있습니다.Date같은 기본적인 방법Date.now(), 또는new Date().getFullYear()(당년도의 경우).

ES6 Javascript를 Angular, React, VueJs 등의 프레임워크와 함께 사용하는 경우.그런 다음 프로젝트 편의를 위해 타사 유틸리티 라이브러리를 통합해야 합니다. DayJS는 불변의 데이터 구조를 가진 가장 인기 있는 경량 라이브러리 중 하나입니다.dayJS얻을 수 있다year다음과 같은 간단한 코드 한 줄에 넣을 수 있습니다.

dayjs().year()

유용한 방법들도 많이 있습니다.그래서 다음 프로젝트에 dayjs를 사용하는 것이 좋습니다.

언급URL : https://stackoverflow.com/questions/6002254/get-the-current-year-in-javascript

반응형