#include "stdafx.h"
class Time
{
private:
int h,m,s;
public:
Time()
{
h=8; m=29; s=20;
}
Time(int h,int m,int s)
{
this->h=h; this->m=m; this->s=s;
}
~Time() // 析构函数: 在释放对象时,自动调用
{
Output();
cout<<"~Time()"<<endl;
}
void Output()
{
cout<<h<<":"<<m<<":"<<s<<endl;
}
};
class Date
{
private:
int y,m,d;
public:
Date(){ y=2024; m=3; d=7; }
Date(int y,int m,int d)
{
this->y=y; this->m=m; this->d=d;
cout<<"Date()"<<endl;
Output();
}
~Date()
{
Output();
cout<<"~Date()"<<endl;
}
void Output()
{
cout<<y<<"-"<<m<<"-"<<d<<endl;
}
};
int Test1()
{
Time t1,t2(8,6,30),t3(8,6,31); // 局部变量:栈
t1.Output();
t2.Output();
t3.Output();
return 0;
}
int Test2()
{
Date d1(2024,3,6),d2(2024,3,7),d3(2024,3,8); // 局部变量:栈
return 0;
}
int main(int argc, char* argv[])
{
Test2();
return 0;
}
Date类是Java中的一个内置类,用于处理日期和时间相关的操作。
Date类可以存储日期和时间的信息,并提供了一些方法来对日期和时间进行操作。例如,Date类可以获取当前的日期和时间,比较两个日期的先后顺序,计算日期的差值等。
使用Date类需要先实例化一个Date对象,可以通过无参构造方法来实例化一个表示当前日期和时间的Date对象,也可以通过传入一个表示特定日期和时间的毫秒数来实例化一个对应的Date对象。
Date类中一些常用的方法包括:
toString()
:将Date对象转换为字符串表示形式,格式为"星期 月 日 时间 时区 年"。getTime()
:获取Date对象的毫秒表示形式。compareTo(Date other)
:比较当前Date对象和参数Date对象的先后顺序,返回一个整数值。equals(Object obj)
:判断当前Date对象是否与参数对象相等。
然而,需要注意的是,Java 8之后,推荐使用新的日期和时间API,如LocalDate、LocalTime和LocalDateTime等,来代替Date类。这些新的API提供了更灵活、更易用、更安全的日期和时间操作方式。