int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
int y2 = d2.get(Calendar.YEAR);
if (d1.get(Calendar.YEAR) != y2) ...{
d1 = (Calendar) d1.clone();
do ...{
days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);//得到当年的实际天数
d1.add(Calendar.YEAR, 1);
} while (d1.get(Calendar.YEAR) != y2);
}
return days;
}
注意:通过上面的方法可以衍生出求任何时间,如要查出邮箱三周之内收到的邮件(得到当前系统时间-再得到三周前时间)用收件的时间去匹配 最好装化成 long去比较
如:1年前日期(注意毫秒的转换)
java.util.Date myDate=new java.util.Date();
long myTime=(myDate.getTime()/1000)-60*60*24*365;
myDate.setTime(myTime*1000);
String mDate=formatter.format(myDate);
7. String 和 Date ,Long 之间相互转换 (最常用)
字符串转化成时间类型(字符串可以是任意类型,只要和SimpleDateFormat中的格式一致即可)
通常我们取时间跨度的时候,会substring出具体时间--long-比较
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("M/dd/yyyy hh:mm:ss a",java.util.Locale.US);
java.util.Date d = sdf.parse("5/13/2003 10:31:37 AM");
long dvalue=d.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mDateTime1=formatter.format(d);
8. 通过时间求时间
年月周求日期
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM F E");
java.util.Date date2= formatter2.parse("2003-05 5 星期五");
SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd");
String mydate2=formatter3.format(date2);
求是星期几
mydate= myFormatter.parse("2001-1-1");
SimpleDateFormat formatter4 = new SimpleDateFormat("E");
String mydate3=formatter4.format(mydate);
9. java 和 具体的数据库结合
在开发web应用中,针对不同的数据库日期类型,我们需要在我们的程序中对日期类型做各种不同的转换。若对应数据库数据是oracle的 Date类型,即只需要年月日的,可以选择使用java.sql.Date类型,若对应的是MSsqlserver 数据库的DateTime类型,即需要年月日时分秒的,选择java.sql.Timestamp类型
你可以使用dateFormat定义时间日期的格式,转一个字符串即可
class Datetest{
*method 将字符串类型的日期转换为一个timestamp(时间戳记java.sql.Timestamp)
*@param dateString 需要转换为timestamp的字符串
*@return dataTime timestamp
public final static java.sql.Timestamp string2Time(String dateString)
throws java.text.ParseException {
DateFormat dateFormat;