记录日期程序怎么写

时间:2025-01-25 13:44:26 单机游戏

记录日期程序可以根据不同的编程语言和需求有多种实现方法。以下是几种常见编程语言的实现示例:

1. 使用C++编写日期类

```cpp

include

include

include

include

class MyDate {

private:

int year;

int month;

int day;

public:

MyDate() : year(0), month(0), day(0) {}

MyDate(int y, int m, int d) : year(y), month(m), day(d) {}

void setDate(int y, int m, int d) {

year = y;

month = m;

day = d;

}

int getYear() const { return year; }

int getMonth() const { return month; }

int getDay() const { return day; }

void addDays(int n) {

while (n > 0) {

day++;

if (day > 31) {

day = 1;

month++;

if (month > 12) {

month = 1;

year++;

}

}

n--;

}

}

void subtractDays(int n) {

while (n > 0) {

day--;

if (day < 1) {

day = 31;

month--;

if (month < 1) {

month = 12;

year--;

}

}

n--;

}

}

int daysBetween(const MyDate& other) const {

int a = year * 365 + year / 4 - year / 100 + year / 400;

int b = other.year * 365 + other.year / 4 - other.year / 100 + other.year / 400;

int c = month * 30 + month / 4;

int d = other.month * 30 + other.month / 4;

return abs(a - b) + abs(c - d);

}

};

int main() {

MyDate today;

today.setDate(2025, 1, 14);

std::cout << "Today's date: " << today.getYear() << "-" << today.getMonth() << "-" << today.getDay() << std::endl;

MyDate tomorrow = today;

tomorrow.addDays(1);

std::cout << "Tomorrow's date: " << tomorrow.getYear() << "-" << tomorrow.getMonth() << "-" << tomorrow.getDay() << std::endl;

return 0;

}

```

2. 使用Python编写记录日期的程序

```python

from datetime import datetime

def get_current_date():

return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

def main():

current_date = get_current_date()

print(f"Current date and time: {current_date}")

diary_content = input("Enter your diary content for today: ")

print(f"Diary content: {diary_content}")

with open("diary.txt", "a", encoding="utf-8") as f:

f.write(f"{current_date}:{diary_content}\n")

if __name__ == "__main__":

main()

```

3. 使用PHP编写记录日期的程序