
假设有两个日期。
第一个日期为:2012年9月13日2时3分4秒
第二个日期为:2012年8月12日0时0分0秒
求二者的时间差的代码如下
import javatextSimpleDateFormat;
import javautilDate;
public class TimeDifference2 {
private static int days; //天数
private static int hours; //时
private static int minutes; //分
private static int seconds; //秒
//第一个字符串
public static final String FIRST = "Sep 13 02:03:04 GMT 2012";
//第二个字符串
public static final String SECOND = "Aug 12 00:00:00 GMT 2012";
public static void main(String[] args) {
//通过字符串创建两个日期对象
Date firstDate = new Date(FIRST);
Date secondDate = new Date(SECOND);
//得到两个日期对象的总毫秒数
long firstDateMilliSeconds = firstDategetTime();
long secondDateMilliSeconds = secondDategetTime();
//得到两者之差
long firstMinusSecond = firstDateMilliSeconds - secondDateMilliSeconds;
//毫秒转为秒
long milliSeconds = firstMinusSecond;
int totalSeconds = (int)(milliSeconds / 1000);
//得到总天数
days = totalSeconds / (360024);
int days_remains = totalSeconds % (360024);
//得到总小时数
hours = days_remains / 3600;
int remains_hours = days_remains % 3600;
//得到分种数
minutes = remains_hours / 60;
//得到总秒数
seconds = remains_hours % 60;
//打印结果
//第一个比第二个多32天2小时3分4秒
Systemoutprint("第一个比第二个多");
Systemoutprintln(days+"天"+hours+"小时"+minutes+"分"+seconds+"秒");
}
}
public class DateSimple {
public static void main(String[] args) {
String startTime = "2012-07-01";
String endTime = "2014-07-31";
String[] arg1 = startTimesplit("-");
String[] arg2 = endTimesplit("-");
int year1 = IntegervalueOf(arg1[0]);
int year2 = IntegervalueOf(arg2[0]);
int month1 = IntegervalueOf(arg1[1]);
int month2 = IntegervalueOf(arg2[1]);
for (int i = year1; i <= year2; i++) {
int monthCount = 12;
int monthStart = 1;
if (i == year1) {
monthStart = month1;
monthCount = 12-monthStart+1;
} else if (i == year2) {
monthCount = month2;
}
for(int j = 0; j < monthCount; j++){
int temp = monthStart+j;
if(temp >=10){
Systemoutprintln(i+"-"+(monthStart+j));
}else{
Systemoutprintln(i+"-0"+(monthStart+j));
}
}
}
}
}
2012-07
2012-08
2012-09
2012-10
2012-11
2012-12
2013-01
2013-02
2013-03
2013-04
2013-05
2013-06
2013-07
2013-08
2013-09
2013-10
2013-11
2013-12
2014-01
2014-02
2014-03
2014-04
2014-05
2014-06
2014-07
比较简单的方法就是使用getTime()获取当前日期的相对毫秒数,再计算差值,最后转换成你需要的数据;
PS
RESULT:
1天0小时0分0秒
相隔的小时数:分:秒 - 24:0:0
public static void main(String[] args) {
// 创建对象
long sTime = SystemcurrentTimeMillis();
for (int i = 0; i < 1000000; i++) {
Systemoutprintln(i);
}
long eTime = SystemcurrentTimeMillis();
Systemoutprintln(((eTime - sTime)/1000/60/60)+"小时");
}
获取时间戳。相减,再把毫秒转换成小时,OK
以上就是关于Java中使用什么方法可以把两个String类型的日期相减求出时间差啊全部的内容,包括:Java中使用什么方法可以把两个String类型的日期相减求出时间差啊、java实现两个日期相减得到中间的年份和月份、java中如何得到两个时间相差多少小时等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)