Java 时间类
日期时间类
Date类

Date对象的创建

Date date=new Date();
System.out.println(date);
运行结果为:Sat Feb 12 23:23:05 CST 2022
Date date=new Date();
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormat.format(date));
运行结果为当前系统时间,此时我的运行结果为:2022-02-12
public class Demo01 {
public static void main(String[] args) {
int year=2000;
int month=2;
int day=3;
String birth= year+"-"+month+"-"+day;
//使用静态方式获取DateFormat对象*/
DateFormat df= DateFormat.getDateInstance();
Date births=null;
try {
births=df.parse(birth);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println(sdf.format(births));
}
}
运行结果:2000/02/03 00:00:00
Date常用方法
public boolean after(Date when) //比较两个时间的先后,如果调用者时间更晚,返回true
public boolean before(Date when) //比较两个时间的先后,如果调用者时间更早,返回true
public int compareTo(Date anotherDate) //如果调用者时间大于比较对象,返回正数,相同返回0,小于返回负数
public long getTime() //得到1970年以来实际经过日期的毫秒数
public void setTime(long time) //以一个毫秒数来设定当前日期
public String toString() //把时间对象以dow mon dd hh:mm:ss zzz yyyy的格式输出(星期,月份,天,时,分,秒,时区,年)
SimpleDateFormat(pattern).parse(str); //将字符串格式化为Date类型,其中pattern是字符串类型,是代表将要格式的字符串str的格式,如”yyyy-MM-dd”,str是将要格式化的字符串
SimpleDateFormat("yyyy-MM-dd").format(date)//将Date类型格式化为字符串类型,其中“yyyy-MM-dd”是要输出的字符串格式,date是要格式化的日期类型

浙公网安备 33010602011771号