public static String change(int second){
int h = 0;
int d = 0;
int s = 0;
int temp = second%3600;
if(second>3600){
h= second/3600;
if(temp!=0){
if(temp>60){
d = temp/60;
if(temp%60!=0){
s = temp%60;
}
}else{
s = temp;
}
}
}else{
d = second/60;
if(second%60!=0){
s = second%60;
}
}
return h+"时"+d+"分"+s+"秒";
}
得到系统当前时间
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
java计算时间差及比较时间大小
比如:现在是2004-03-26 13:31:40
过去是:2004-01-02 11:30:24
我现在要获得两个日期差,差的形式为:XX天XX小时XX分XX秒
方法一:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try
{
Date d1 = df.parse("2004-03-26 13:31:40");
Date d2 = df.parse("2004-01-02 11:30:24");
long diff = d1.getTime() - d2.getTime();
long days = diff / (1000 * 60 * 60 * 24);
}
catch (Exception e)
{
}
方法二: SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date now = df.parse("2004-03-26 13:31:40");
java.util.Date date=df.parse("2004-01-02 11:30:24");
long l=now.getTime()-date.getTime();
long day=l/(24*60*60*1000);
long hour=(l/(60*60*1000)-day*24);
long min=((l/(60*1000))-day*24*60-hour*60);
long s=(l/1000-day*24*60*60-hour*60*60-min*60);
System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");
方法三:
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date begin=dfs.parse("2004-01-02 11:30:24");
java.util.Date end = dfs.parse("2004-03-26 13:31:40");
long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒
long day1=between/(24*3600);
long hour1=between%(24*3600)/3600;
long minute1=between%3600/60;
long second1=between%60/60;
System.out.println(""+day1+"天"+hour1+"小时"+minute1+"分"+second1+"秒");
时间比较
import java.text.*;
import java.util.*;
public static void main(String arg[])
{
String date = "";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
java.util.Date dd = Calendar.getInstance().getTime();
date = sdf.format(dd);
System.out.println(date);
boolean flag = isDateBefore(date+" 09:01:00");
System.out.println(flag);
}
public static boolean isDateBefore(String date2)
{
try{
Date date1 = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
System.out.println(date1.before(df.parse(date2)));
return date1.before(df.parse(date2));
}catch(ParseException e){
System.out.print(e.getMessage());
return false;
}
}
}
public static boolean isDateAfter(String date2){
try{
Date date1 = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
System.out.println(date1.after(df.parse(date2)));
return date1.after(df.parse(date2));
}catch(ParseException e){
System.out.print(e.getMessage());
return false;
}
}
上下班时间可以通过这个时间来比较是否迟到或早退