java.util.Date
日期操作
Java中的时间
Java中的时间使用标准类库的Date类表示,是用距离一个固定时间点的 毫秒数(可正可负,long类型)表达一个特定的时间点;
固定的时间点叫纪元(epoch),是UTC时间1970年 1月 1日 00:00:00;
UTC(Universal Time Coordinated世界调整时间)与GMT(Greenwich Mean Time格林威治时间)一样,是一种具有实际目的的科学标准时间。
Date的每一个实例用于表示一个具体的时间,内部维护了一个 long值,
记录的是自1970年1月1日00:00:00到其表示的时间之间所经过的毫秒
1. 将Date转换为Long类型,Date类提供了getTime()方法,返回long类型1970年1月1日00:00:00截至到现在的毫秒数
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
//将Date转换为Long类型,Date类提供了getTime()方法,返回long类型
//1970年1月1日00:00:00截至到现在的毫秒数
long time = date.getTime();
System.out.println(time);
}
2.将long类型转换为Date类型,Date类提供了setTime(long time)方法
public static void main(String[] args) {
Date date = new Date();
long time = date.getTime();
//将long类型转换为Date类型,Date类提供了setTime(long time)方法
date.setTime(time);
System.out.println(date);
}
- 日期转换格式:
通过SimpleDateFormat类可以将Date类型转化为字符串,也可以将字符串转化为Date类型
Date类型转换为字符串
//Date类型转换为字符串
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
//将date转化为 年-月-日 时:分:秒
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年-MM月-dd日 HH时:mm分:ss秒");
String formatDate = simpleDateFormat.format(date);
System.out.println(formatDate);
}
字符串转换Date类型
//字符串转换Date类型
public static void main(String[] args) throws ParseException {
Date date = new Date();
System.out.println(date);
//将date转化为 年-月-日 时:分:秒
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年-MM月-dd日 HH时:mm分:ss秒");
String formatDate = simpleDateFormat.format(date);
System.out.println(formatDate);
//将字符串转化为Date
//注意:字符串中的时间格式需要和创建simpleDateFormat的格式相同 ("yyyy年-MM月-dd日 HH时:mm分:ss秒")
String str = "2008年-08月-08日 08时:08分:08秒";
Date parsedDate = simpleDateFormat.parse(str);
System.out.println(parsedDate);
}
- 要求用户输入自己的生日,格式例如:2002-08-08
- 然后通过程序计算输出至今为止你一共活了多少天?
- 在输出自己出生那一天的10000天的纪念日是那一天?
/*
* 要求用户输入自己的生日,格式例如:2002-08-08
然后通过程序计算输出至今为止你一共活了多少天?
在输出自己出生那一天的10000天的纪念日是那一天?
* */
public static void main(String[] args) throws ParseException {
Scanner input = new Scanner(System.in);
System.out.println("请输入您的生日(格式:2002-08-08)");
String birthDay = input.nextLine();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = simpleDateFormat.parse(birthDay);
long birthTime = parsedDate.getTime();
long now = System.currentTimeMillis();
long liveTime = now - birthTime;
System.out.println("至今为止你一共活了"+liveTime / 1000 / 60 / 60 / 24+"天");
long commemorationDayTime = 10000L*24*60*60*1000;
Date date = new Date();
date.setTime(commemorationDayTime + birthTime);
String commemorationDay = simpleDateFormat.format(date);
System.out.println("10000天的纪念日是"+commemorationDay);
}