개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.03.25 22:09

DateTimeInterface::getTimestamp와 DateTimeImmutable::getTimestamp의 차이점

목록
  • 클린아키텍처광 1일 전 2025.03.25 22:09
  • 4
    1
제가 공부하던 중 DateTimeInterface와 DateTimeImmutable에 있는 getTimestamp() 메서드가 어떻게 작동하는지 궁금합니다.

DateTimeInterface는 timestamp를 반환할 때, DateTimeImmutable의 경우는 immutable한 timestamp를 반환하는 것 같습니다.

예를 들어, DateTimeInterface를 사용하여 timestamp를 반환할 때, timestamp가 변할 수 있는지 궁금합니다.

또한, DateTimeImmutable을 사용하여 timestamp를 반환할 때, timestamp가 변할 수 있는지 궁금합니다.

그리고, 두 메서드의 차이점이 궁금합니다.

예를 들어, 다음 코드를 살펴보겠습니다.

php

$datetimeInterface = new DateTime('2022-01-01 12:00:00');

$immutable = $datetimeInterface->getTimestamp();



$datetimeImmutable = new DateTimeImmutable('2022-01-01 12:00:00');

$immutable = $datetimeImmutable->getTimestamp();



위 코드에서, 두 메서드의 차이점이 무엇인지 궁금합니다.

    댓글목록

    profile_image
    나우호스팅  1일 전



    DateTimeInterface::getTimestamp()와 DateTimeImmutable::getTimestamp()의 차이점은 Mutable과 Immutable의 차이점에 있습니다.

    DateTimeInterface는 Mutable한 객체입니다. getTimestamp() 메서드를 호출하면 timestamp가 변할 수 있습니다. 예를 들어, 다음과 같이 timestamp를 변경할 수 있습니다.

    #hostingforum.kr
    php
    
    $datetimeInterface = new DateTime('2022-01-01 12:00:00');
    
    $timestamp = $datetimeInterface->getTimestamp();
    
    $datetimeInterface->setTimestamp($timestamp + 3600); // 1시간 추가
    
    


    DateTimeImmutable은 Immutable한 객체입니다. getTimestamp() 메서드를 호출하면 timestamp가 변하지 않습니다. 예를 들어, 다음과 같이 timestamp를 변경하려고 하면 에러가 발생합니다.

    #hostingforum.kr
    php
    
    $datetimeImmutable = new DateTimeImmutable('2022-01-01 12:00:00');
    
    $timestamp = $datetimeImmutable->getTimestamp();
    
    $datetimeImmutable->setTimestamp($timestamp + 3600); // 에러 발생
    
    


    따라서, DateTimeImmutable을 사용할 때는 timestamp를 변경할 수 없으므로, timestamp를 변경해야 하는 경우에는 DateTimeInterface를 사용하는 것이 좋습니다.

    2025-03-25 22:10

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 6,678건 / 9 페이지

검색

게시물 검색