import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample {
public static void main(String[] args) {
String dateStart = "2013-02-19 09:29:58";
String dateStop = "2013-02-20 11:31:48";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//毫秒ms
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print("两个时间相差:");
System.out.print(diffDays + " 天, ");
System.out.print(diffHours + " 小时, ");
System.out.print(diffMinutes + " 分钟, ");
System.out.print(diffSeconds + " 秒.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
获取当前时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(date);
例子
package cn.service.impl;
import cn.dao.IDentDao;
import cn.pojo.Dog;
import cn.service.DogMessage;
import cn.service.DogZhanShiService;
import com.alibaba.fastjson.JSON;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class DogZhanShiServiceImpl implements DogZhanShiService {
@Resource(name = "IDentDao")
private IDentDao dd;
public IDentDao getDd() {
return dd;
}
public void setDd(IDentDao dd) {
this.dd = dd;
}
public String getAll() {
List<DogMessage> ss = new ArrayList<DogMessage>();
for (Dog dog:dd.getss()) {
DogMessage d = new DogMessage();
d.setDogPrice(dog.getDogPrice());
d.setDogKind(dd.getDogType(dog.getDogKind()).getDtype());
String a = d.setDogUploading(dog.getDogUploading());
d.setDogTupian(dog.getDogTupian());
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(date);
// System.out.println(format);
// System.out.println(a);
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse(a);
d2 = sdf.parse(format);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24*60;
long diffDays = diff / (24 * 60 * 60 * 1000)*24*60;
long diffSum = diffMinutes + diffHours + diffDays + diffSeconds;
d.setDogUploading(String.valueOf(diffSum));
// System.out.print("两个时间相差:");
// System.out.print(diffDays + " 天, ");
// System.out.print(diffHours + " 小时, ");
// System.out.print(diffMinutes + diffHours + diffDays + diffSeconds + " 分钟前");
// System.out.print(diffSeconds + " 秒.");
} catch (ParseException e) {
e.printStackTrace();
}
ss.add(d);
}
String a = JSON.toJSONString(ss);
return a;
}
}