요일과 월을 얻는 방법은 무엇입니까? 다른 질문은 필요한 정보를

Javascript에 대해 잘 모르고 내가 찾은 다른 질문은 필요한 정보를 얻는 것뿐만 아니라 날짜 작업과 관련이 있습니다.

객관적인

아래 형식으로 날짜를 얻고 싶습니다.

2011 년 1 월 27 일 목요일 17:42:21에 인쇄 됨

지금까지 다음을 얻었습니다.

var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();

h = checkTime(h);
m = checkTime(m);
s = checkTime(s);

var prnDt = "Printed on Thursday, " + now.getDate() + " January " + now.getFullYear() + " at " + h + ":" + m + ":" s;

이제 요일과 월 (이름)을 얻는 방법을 알아야합니다.

그것을 만드는 간단한 방법이 있습니까, 아니면 단순히 now.getMonth()및 사용하여 올바른 값으로 인덱싱하는 배열 사용을 고려 now.getDay()할까요?



답변

예, 어레이가 필요합니다.

var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];

또는 date.js 라이브러리를 사용할 수 있습니다 .


편집하다:

이러한 기능을 자주 사용하려면 Date.prototype접근성 을 위해 확장 하는 것이 좋습니다.

(function() {
    var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

    Date.prototype.getMonthName = function() {
        return months[ this.getMonth() ];
    };
    Date.prototype.getDayName = function() {
        return days[ this.getDay() ];
    };
})();

var now = new Date();

var day = now.getDayName();
var month = now.getMonthName();


답변

표준 자바 스크립트 Date 클래스를 사용합니다. 어레이가 필요 없습니다. 추가 라이브러리가 필요하지 않습니다.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString을 참조 하십시오.

var options = {  weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
var prnDt = 'Printed on ' + new Date().toLocaleTimeString('en-us', options);

console.log(prnDt);


답변

또한 할 수있는 한 가지는 다음과 같이 요일을 반환하도록 날짜 개체를 확장하는 것입니다.

Date.prototype.getWeekDay = function() {
    var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    return weekday[this.getDay()];
}

따라서 date.getWeekDay (); 만 호출 할 수 있습니다.


답변

@ L-Ray 가 이미 제안 했듯이 moment.js 도 살펴볼 수 있습니다.

견본

var today = moment();
var result = {
  day: today.format("dddd"),
  month: today.format("MMM")
}

document.write("<pre>" + JSON.stringify(result,0,4) + "</pre>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>


답변

불행히도 Datejavascript의 객체는 숫자 형식으로 만 월에 대한 정보를 반환합니다. 당신이 할 수있는 더 빠른 일은 월의 배열을 생성하고 (자주 변경해서는 안됩니다!) 숫자에 따라 이름을 반환하는 함수를 생성하는 것입니다.

이 같은:

function getMonthNameByMonthNumber(mm) {
   var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

   return months[mm];
}

따라서 코드는 다음과 같습니다.

var prnDt = "Printed on Thursday, " + now.getDate() + " " + getMonthNameByMonthNumber(now.getMonth) + " "+  now.getFullYear() + " at " + h + ":" + m + ":" s;


답변

var GetWeekDays = function (format) {
    var weekDays = {};

    var curDate = new Date();
    for (var i = 0; i < 7; ++i) {
        weekDays[curDate.getDay()] = curDate.toLocaleDateString('ru-RU', {
            weekday: format ? format : 'short'
        });

        curDate.setDate(curDate.getDate() + 1);
    }

    return weekDays;
};

me.GetMonthNames = function (format) {
    var monthNames = {};

    var curDate = new Date();
    for (var i = 0; i < 12; ++i) {
        monthNames[curDate.getMonth()] = curDate.toLocaleDateString('ru-RU', {
            month: format ? format : 'long'
        });

        curDate.setMonth(curDate.getMonth() + 1);
    }

    return monthNames;
};


답변

http://phrogz.net/JS/FormatDateTime_JS.txt 를 사용하여 다음을 수행 할 수 있습니다.

var now = new Date;
var prnDt = now.customFormat( "Printed on #DDDD#, #D# #MMMM# #YYYY# at #hhh#:#mm#:#ss#" );