把string型转为Date型
- Calendar c1 = Calendar.getInstance();
- c1.set(2005, 1, 1);
- System.out.println(c1.getTime());
Calendar c1 = Calendar.getInstance();
c1.set(2005, 1, 1);
System.out.println(c1.getTime());
计算两个日期的时间差
- Calendar c1 = Calendar.getInstance();
- c1.set(2005, 1, 1);
- Date dateCreatedStop = new java.sql.Date(new java.util.Date().getTime());
- Calendar c2 = Calendar.getInstance();
- c2.setTime(dateCreatedStop);
- long l1 = c1.getTimeInMillis();
- long l2 = c2.getTimeInMillis();
- // 计算天数
- long days = (l2 - l1) / (24 * 60 * 60 * 1000);
- System.out.println(days);
Calendar c1 = Calendar.getInstance();
c1.set(2005, 1, 1);
Date dateCreatedStop = new java.sql.Date(new java.util.Date().getTime());
Calendar c2 = Calendar.getInstance();
c2.setTime(dateCreatedStop);
long l1 = c1.getTimeInMillis();
long l2 = c2.getTimeInMillis();
// 计算天数
long days = (l2 - l1) / (24 * 60 * 60 * 1000);
System.out.println(days);
输出结果为两个日期相差的天数
一个带main方法的类
- import java.util.*;
- /**
- * 计算两个日期之间相差的天数
- */
- public class TestDate {
- public static void main(String[] args) {
- // 设置两个日期
- // 日期:2009年3月11号
- Calendar c1 = Calendar.getInstance();
- c1.set(2009, 3, 1);
- // 日期:2010年4月1号
- Calendar c2 = Calendar.getInstance();
- c2.set(2009, 3, 2);
- // 转换为相对时间
- long l1 = c1.getTimeInMillis();
- long l2 = c2.getTimeInMillis();
- // 计算天数
- long days = (l2 - l1) / (24 * 60 * 60 * 1000);
- System.out.println(days);
- }
- }