日期类
Date和long的相互转换
public class lianxi {
public static void main(String[] args) {
//Date转long
long time = new Date().getTime();
System.out.println(time);
//long转Date
long i=10000000000l;
Date date = new Date(i);
System.out.println(date);
}
}
格式化日期类型
public class lianxi {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat();
String format1 = format.format(date);
System.out.println(format1);
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss E w W F");
String format3 = format2.format(date);
System.out.println(format3);
}
}
输出结果:19-5-8 下午9:13
2019-05-08 21-13-02 星期三 19 2 2
解析时间:
public class lianxi {
public static void main(String[] args) throws ParseException {
String str="2019-05-08 21:15:28";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parse = format.parse(str);
System.out.println(parse);
}
}
练习:输入一个日期算一下到今天多少天了
public class lianxi {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的日期,格式2018年08月08日");
String string = sc.nextLine();
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
Date date = format.parse(string);
long time = date.getTime();
long time2 = System.currentTimeMillis();
long l= time2 - time;
System.out.println("距现在"+l/1000/60/60/24+"天");
}
}
练习:输入一个年份,计算该年份的二月有多少天
方法一:
public class lianxi {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份");
int i = sc.nextInt();
if (i%4==0&&i%100!=0||i%400==0){
System.out.println(i+"二月份有29天");
}else{
System.out.println(i+"二月有28天");
}
}
}
输出结果
请输入年份
2019
2019二月有28天
方法二:面向对象的思想,
public class lianxi {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入年份");
int i = sc.nextInt();
Calendar instance = Calendar.getInstance();
instance.set(i,2,1);
instance.add(Calendar.DAY_OF_MONTH,-1);
System.out.println(i+"年一共有"+instance.get(Calendar.DAY_OF_MONTH)+"天");
}
}
JDK1.8 之后,提供了一套全新的时间日期API 也推荐你使用JDK1.8所提供的
public class lianxi {
public static void main(String[] args) throws ParseException {
LocalDate start = LocalDate.of(1998, 11, 11);
LocalDate now = LocalDate.now();
Period between = Period.between(start, now);
int years = between.getYears();
int months = between.getMonths();
int days = between.getDays();
System.out.println("你距出生"+years+"年"+months+"月"+days+"天");
}
}