javascript当中的setDate()

使用setDate(),如果传入的值大于本月的天数,则javascript将从本月的第一天开始计数,那么使用使用setDate(28)方法,则并不是表示1月15号之后的28天,而是表示距离1月1日之后的28天,如果我们要计算的是当前日期之后的28天,就需要先取出当前的天数,再用当前的天数加上28。因此,要计算1月15日之后的28天,应该使用setDate(15+28)。

如果我们想获得当前日期之前的28天,只需要用当前的日期减去28即可。


类似的方法和原则也适用于setMonth()方法。

好的,我们可以创建一个名为`Date`的时间类,包含`year`, `month`, 和 `day` 作为私有数据成员。以下是该类的简单实现: ```cpp #include <iostream> class Date { private: int year; int month; int day; public: // 构造函数,初始化日期 Date(int y = 0, int m = 1, int d = 1) : year(y), month(m), day(d) {} // 设置日期 void setDate(int new_year, int new_month, int new_day) { year = new_year; month = new_month; day = new_day; } // "年月日"格式显示日期 std::string showDate() const { return std::to_string(year) + "年" + std::to_string(month) + "月" + std::to_string(day) + "日"; } // 使日期增加一天 void addOneDay() { if (day != 31 && ((month == 1 && day <= 28) || (month > 1 && (month % 2 != 0 || (month == 2 && day <= 29))))) { // 普通月份或闰年的2月 day++; } else if (month == 2 && isLeapYear()) { // 跳过闰年的2月最后一天 day = 1; } else if (month == 2 && isLeapYear() && day == 29) { // 闰年的2月29日 day = 1; } else if (month == 12 && day == 31) { // 如果已经是12月31日,则进入下一年 day = 1; month = 1; } } // 判断是否为闰年 bool isLeapYear() const { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } }; // 主函数 int main() { Date myDate(2023, 3, 5); // 创建一个日期对象,设定初始日期 myDate.setDate(2024, 2, 29); // 设置特定日期 std::cout << "初始日期: " << myDate.showDate() << std::endl; // 显示当前日期 myDate.addOneDay(); // 增加一天 std::cout << "增加一天后的日期: " << myDate.showDate() << std::endl; // 再次显示日期 return 0; } ``` 这个程序首先定义了一个`Date`类,包含了设置日期、显示日期和增加一天的功能。在`main`函数中,我们创建了一个日期对象并设置了日期,然后展示了原始日期和增加一天后的日期。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值