Programing

Moment.js를 날짜 객체로 변환

lottogame 2020. 10. 3. 09:44
반응형

Moment.js를 날짜 객체로 변환


Moment.js를 사용하여 올바른 순간 객체를 시간대가있는 날짜 객체로 변환 할 수 없습니다. 정확한 날짜를 알 수 없습니다.

예:

var oldDate = new Date(),
    momentObj = moment(oldDate).tz("MST7MDT"),
    newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())

이것을 사용하여 순간 객체를 날짜 객체로 변환합니다.

에서 http://momentjs.com/docs/#/displaying/as-javascript-date/

moment().toDate();

수율 :

Tue Nov 04 2014 14:04:01 GMT-0600 (CST)

원하는 영역에 대한 데이터로 순간 시간대초기화 경우 코드가 예상대로 작동합니다.

순간을에서 출력의 두 번째 줄에 반영되는 시간대로 올바르게 변환하고 있습니다 momentObj.format().

UTC로 전환하면 오프셋이 떨어질뿐만 아니라 UTC 시간대로 다시 변경됩니다. 그렇게하려는 경우 원래 .tz()통화 가 전혀 필요하지 않습니다 . 당신은 할 수 있습니다 moment.utc().

아마도 출력 형식 문자열을 변경하려는 것일까 요? 그렇다면 format메소드에 원하는 매개 변수를 지정하십시오 .

momentObj.format("YYYY-MM-DD HH:mm:ss")

코드의 마지막 줄과 관련 하여을 Date사용하여 객체 로 돌아갈 때 toDate()moment.js의 동작을 포기하고 JavaScript의 동작으로 돌아갑니다. JavaScript Date개체는 항상 실행중인 컴퓨터의 현지 시간대로 인쇄됩니다. moment.js가 할 수있는 일은 없습니다.

다른 몇 가지 사항 :

  • 순간 생성자는 동안 Date, 그것은 하나를 사용하지 않는 것이 가장 좋습니다. "지금"에는를 사용하지 마십시오 moment(new Date()). 대신 moment(). 둘 다 작동하지만 불필요하게 중복됩니다. 문자열에서 구문 분석하는 경우 해당 문자열을 순간으로 직접 전달하십시오. Date처음 으로 파싱하지 마십시오 . 순간의 파서가 훨씬 더 안정적임을 알 수 있습니다.

  • 같은 시간대 MST7MDT는 이전 버전과의 호환성을 위해 존재합니다. POSIX 스타일 시간대에서 비롯되며 그중 일부만 TZDB 데이터에 있습니다. 꼭 필요한 경우가 아니라면 America/Denver.


.toDate 나를 위해 실제로 작동하지 않았으므로 여기에 내가 한 일이 있습니다.

futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))

도움이 되었기를 바랍니다


momentjs는 자바 스크립트 날짜 개체를 제어 할 수 없기 때문에 이에 대한 해결 방법을 찾았습니다.

const currentTime = new Date();    
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");
const convertTimeObject = new Date(convertTime);

변환 된 시간이 포함 된 자바 스크립트 날짜 개체를 제공합니다.


내 날짜 문자열에 시간대 정보가 필요했습니다. 나는 원래 사용하고 moment.tz(dateStr, 'America/New_York').toString();있었지만 그 문자열을 순간으로 다시 공급하는 것에 대한 오류가 발생하기 시작했습니다.

나는 시도 moment.tz(dateStr, 'America/New_York').toDate();했지만 필요한 시간대 정보를 잃어 버렸습니다.

순간으로 되돌릴 수있는 시간대와 함께 사용 가능한 날짜 문자열을 반환 한 유일한 솔루션 moment.tz(dateStr, 'America/New_York').format();


moment는 2018 년 6 월에 js lib를 업데이트했습니다.

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

Angular5 +를 자유롭게 사용할 수 있다면 여기의 시간대 기능보다 datePipe 기능을 더 잘 사용하십시오. 내 프로젝트가 Angular2로만 제한되기 때문에 moment.js를 사용해야합니다.


let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();

멋지고 깨끗한 !!!!


시도 ( format단계 없이 )

new Date(moment())

var d = moment.tz("2019-04-15 12:00", "America/New_York");

console.log( new Date(d) );
console.log( new Date(moment()) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>

참고URL : https://stackoverflow.com/questions/17987647/moment-js-transform-to-date-object

반응형