java计算时间差及⽐较时间⼤⼩javaz中对⽇期时间的处理⽐较多,代码中列出了3中⽇期时间计算差值的⽅法。
⽐如:现在是2004-03-26 13:31:40
过去是:2004-01-02 11:30:24
我现在要获得两个⽇期差,差的形式为:XX天XX⼩时XX分XX秒
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");java时间日期格式转换
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 Time()-Time();
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=(Time()-Time())/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+"秒");
====================================================
java ⽐较时间⼤⼩
String s1="2008-01-25 09:12:09";
String s2="2008-01-29 09:12:11";
java.util.Calendar c1=java.Instance();
java.util.Calendar c2=java.Instance();
try
{
c1.setTime(df.parse(s1));
c2.setTime(df.parse(s2));
}ParseException e){
}
int result=c1pareTo(c2);
if(result==0)
System.out.println("c1相等c2");
else if(result<0)
System.out.println("c1⼩于c2");
else
System.out.println("c1⼤于c2");
转⾃:jackmlw.blog.sohu/140277739.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。