java 格式化时间计算
package com.roshi.utils.common;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtilsCom {
/**
* 格式化时间
* @param date
* @return
* @author lzq
* @throws ParseException
* @date 2016年10月14日
*/
public static String timeFormat(Date date) throws ParseException{
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
String str="";
long from = date.getTime();
String d=new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
long to = simpleFormat.parse(d).getTime();
int day = (int) ((to - from)/(1000 * 60 * 60 * 24));
// long hour=(l/(60*60*1000)-day*24);
day = Math.abs(day);
if(day==0){
str="今天";
}
if(day>0&&day<=6){
str=day+"天";
}
if(day>6&&day<30){
str=day/7+"周";
}
if(day>=30){
long a = day/30;
str=a+"个月";
if(a>=12){
str=a/12+"年";
}
}
return str;
}
/**
* 格式化时间
* @param date
* @return
* @author lzq
* @throws ParseException
* @date 2016年10月14日
*/
public static String timeFormat(String time) throws ParseException{
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
String str="";
long from = simpleFormat.parse(time).getTime();
String d=new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
long to = simpleFormat.parse(d).getTime();
int day = (int) ((to - from)/(1000 * 60 * 60 * 24));
// long hour=(l/(60*60*1000)-day*24);
day = Math.abs(day);
if(day==0){
str="今天";
}
if(day>0&&day<=6){
str=day+"天";
}
if(day>6&&day<30){
str=day/7+"周";
}
if(day>=30){
long a = day/30;
str=a+"个月";
if(a>=12){
str=a/12+"年";
}
}
return str;
}
public static void main(String [] args) throws ParseException{
String d1 = "2016-10-14";
String d2 = "2016-10-15";
/* 先转成毫秒并求差 */
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String d=new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
long m = sdf.parse(d).getTime()- sdf.parse(d2).getTime();
/* 根据你的需求进行单位转换 */
System.out.println("相差毫秒数:"+ m );
System.out.println("相差天数:"+ ( m / (1000 * 60 * 60 * 24) ) );
String strDate = "2016-10-25";
Date date=sdf.parse(strDate);
System.out.println(timeFormat("2016-10-13"));
}
}