std::chrono::year_month_day_last

std::chrono::year_month_day_last (연·월 마지막 날 클래스)

특정 연도와 월의 마지막 날을 나타내는 클래스예요. 필드 기반 시점 타입으로, 분해능은 std::chrono::days이고 월의 마지막 날만 나타낼 수 있다는 제한이 있어요. C++20의 chrono 달력 시스템에서 월말(month end) 날짜를 표현해요.

출처: cppreference

본문

<chrono> 헤더에 정의돼 있고, 특정 연도와 월의 마지막 날을 나타내요.

class year_month_day_last;

필드 기반 시점 타입이고, 분해능은 std::chrono::days예요. 다만 한 달의 마지막 날만 나타낼 수 있다는 제한이 있어요. std::chrono::years·std::chrono::months 중심 산술이 직접 지원되고, std::chrono::sys_days로의 암시적 변환 덕분에 std::chrono::days 중심 산술도 효율적으로 수행할 수 있어요. year_month_day_last는 TriviallyCopyable한 StandardLayoutType이에요.

멤버 함수:

  • 생성자: year_month_day_last 객체를 만들 수 있어요.
  • operator+=, operator-=: 시점을 몇 달 또는 몇 년만큼 수정해요.
  • year(), month(), month_day_last(): 이 객체의 필드들에 접근해요.
  • operator sys_days, operator local_days: std::chrono::time_point로 변환해요.
  • ok: 이 객체가 유효한 날짜를 나타내는지 확인해요.

비멤버 함수:

  • operator==, operator<=> (C++20): 두 year_month_day_last 값을 비교해요.
  • operator+, operator- (C++20): year_month_day_last에 몇 년 또는 몇 달을 더하거나 빼요.
  • operator<< (C++20): year_month_day_last를 스트림에 출력해요.

헬퍼 클래스:

  • std::formatter<std::chrono::year_month_day_last> (C++20): year_month_day_last 포맷 지원.
  • std::hash<std::chrono::year_month_day_last> (C++26): 해시 지원.

last라는 특별한 객체를 day 위치에 사용해 "그 달의 마지막 날"을 나타내요. 예제를 보면요.

#include <chrono>
#include <iostream>

int main()
{
    const auto ymd = std::chrono::year_month_day
    {
        std::chrono::floor<std::chrono::days>(std::chrono::system_clock::now())
    };

    const std::chrono::year_month_day_last ymdl
    {
        ymd.year(), ymd.month() / std::chrono::last
    };

    std::cout << "The last day of present month (" << ymdl << ") is: "
              << std::chrono::year_month_day{ymdl}.day() << '\n';

    using namespace std::chrono;
    constexpr std::chrono::year_month_day_last
        ymdl1 = 2023y / February / last,
        ymdl2 = last / February / 2023y,
        ymdl3 = February / last / 2023y;
    static_assert(ymdl1 == ymdl2 && ymdl2 == ymdl3);
}

가능한 출력:

The last day of present month (2023/Aug/last) is: 31

lastday를 놓을 수 있는 곳이면 어디든 배치할 수 있고, year_month_day{ymdl}로 변환하면 실제 마지막 날짜를 얻을 수 있어요.

더 알아보기 (Learn more)

cppreference