简体   繁体   English

问与答:我如何知道一个月的最后一天是哪一天?

[英]Q&A: How do I figure out what the last day of the month is?

I was trying to write a roll-your-own timezone converter and I needed a way of determining what the last possible day of the month was.我正在尝试编写一个自己滚动的时区转换器,我需要一种方法来确定该月的最后一天是什么。 Upon some research, I discovered the formulas for finding a leap year.经过一番研究,我发现了寻找闰年的公式。

It's a small contribution, but maybe I'll save someone else the 20 minutes it took me to figure out and apply it.这是一个很小的贡献,但也许我会节省其他人我花了 20 分钟弄清楚并应用它的时间。

This code accepts a signed short month, indexed at 0 (0 is January) and an int year that is indexed as 0 as well (2012 is 2012).此代码接受一个有符号的短月,索引为 0(0 是一月)和一个索引为 0 的 int 年(2012 年是 2012 年)。

It returns a 1 indexed day (the 27th is the 27th, but in SYSTEMTIME structures, etc., you usually need 0 indexed - just a head's up).它返回 1 索引日(27 日是 27 日,但在 SYSTEMTIME 结构等中,您通常需要 0 索引 - 只是抬头)。

short _get_max_day(short month, int year) {
    if(month == 0 || month == 2 || month == 4 || month == 6 || month == 7 || month == 9 || month == 11)
        return 31;
    else if(month == 3 || month == 5 || month == 8 || month == 10)
        return 30;
    else {
        if(year % 4 == 0) {
            if(year % 100 == 0) {
                if(year % 400 == 0)
                    return 29;
                return 28;
            }
            return 29;
        }
        return 28;
    }
}

What about 关于什么

#include <time.h>
#include <iostream>

int LastDay (int iMonth, int iYear)
{
    struct tm when;
    time_t lastday;

    // Set up current month
    when.tm_hour = 0;
    when.tm_min = 0;
    when.tm_sec = 0;
    when.tm_mday = 1;

    // Next month 0=Jan
    if (iMonth == 12)
    {
        when.tm_mon = 0;
        when.tm_year = iYear - 1900 + 1;
    }
    else
    {
        when.tm_mon = iMonth;
        when.tm_year = iYear - 1900;
    }
    // Get the first day of the next month
    lastday = mktime (&when);

    // Subtract 1 day
    lastday -= 86400;

    // Convert back to date and time
    when = *localtime (&lastday);

    return when.tm_mday;
}

int _tmain(int argc, _TCHAR* argv[])
{
    for (int m = 1; m <= 12; m++)
        std::cout << "Last day of " << m << " is " << LastDay (m, 2002) << std::endl;

    return 0;
}

It prints out (for year 2002)... 打印出来(2002年)......

Last day of 1 is 31
Last day of 2 is 28
Last day of 3 is 31
Last day of 4 is 30
Last day of 5 is 31
Last day of 6 is 30
Last day of 7 is 31
Last day of 8 is 31
Last day of 9 is 30
Last day of 10 is 31
Last day of 11 is 30
Last day of 12 is 31

I use a simple function that returns the whole date in the from of a (Standard) COleDateTime. 我使用一个简单的函数,它返回(标准)COleDateTime的整个日期。 It may not be as fast other options, but it is very effective, works for leap years and pretty fool proof. 它可能不是那么快的其他选择,但它非常有效,适用于闰年和非常简单的证明。

This is the Code that I am using: 这是我正在使用的代码:

COleDateTime get_last_day_of_month(UINT month, UINT year)    
{
if(month == 2)
    {                                               // if month is feb, take last day of March and then go back one day
        COleDateTime    date(year, 3, 1, 0, 0, 0);  // 1 March for Year
        date -= 1;                                  // go back one day (the standard class will take leap years into account)
        return date;
    }
    else if(month == 4 || month == 6 || month == 9 || month == 11) return COleDateTime(year, month, 30, 0, 0, 0);
    else return COleDateTime(year, month, 31, 0, 0, 0);
}
import datetime 
from datetime import date
from dateutil.relativedelta import relativedelta

year = int((date.today()).strftime("%Y"))
month = list(range(1, 13, 1))
YearMonthDay = [(datetime.datetime(year, x, 1) + relativedelta(day=31)).strftime("%Y%m%d") for x in month]
print(YearMonthDay)

['20220131', '20220228', '20220331', '20220430', '20220531', '20220630', '20220731', '20220831', '20220930', '20221031', '20221130', '20221231'] ['20220131', '20220228', '20220331', '20220430', '20220531', '20220630', '20220731', '20220831', '20220930', '20221031', '2021'

In C++20:在 C++20 中:

#include <chrono>

std::chrono::day
get_max_day(std::chrono::month m, std::chrono::year y)
{
    return (y/m/std::chrono::last).day();
}

If you really need it with a type-unsafe API:如果你真的需要一个类型不安全的 API:

int
get_max_day(int m, int y)
{
    return unsigned{(std::chrono::last/m/y).day()};
}
Word Year, Month, Day;
TDateTime datum_tdatetime = Date();

// first day of actual month
datum_tdatetime.DecodeDate(&year, &month, &day);
day = 1;
datum_tdatetime = EncodeDate(year, month, day);
// last day of previous month
datum_tdatetime -= 1;
// first day of previous month
datum_tdatetime.DecodeDate(&year, &month, &day);
day = 1;
datum_tdatetime = EncodeDate(year, month, day);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使继承相同基类的类的虚拟方法弄清楚如何处理其参数? - How do I make virtual methods of classes that inherit the same base class figure out what to do with their argument? 一个月的最后一天? - Last day of a month? 当一天设置为当月的第一天并减少时,如何解决这个问题,它应该成为上个月的最后一天? - how to solve this question when a day is set to the first day of the month and decremented, it should become the last day of the previous month? 它也不是最大/最小代码我如何找出这个代码? - It is nor max/min code how do i figure out this code? 无法找出要为函数的最后一个代码字符串写什么 - cant figure out what to write for the last string of code for function 如何重载由一天和一个月组成的对象的前和后增量运算符,并将其打印为std :: string? - How do I overload the pre and post increment operators for an object that is composed of a day and month to be printed as a std::string? 无法弄清楚如何执行此代码 - Cannot figure out how to do this code 我无法弄清楚是什么导致了 output 问题或如何解决它 (C++) - I cant figure out what is causing the output problem or how to fix it (C++) 为什么不专门化 function 模板? (问答) - Why not specialize function templates? (Q&A) 将成员函数指针作为参数传递? Q&A - Passing a member function pointer as a parameter? Q&A
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM