publicstaticStringgetDurationTimeStamp(Stringdate){StringtimeDifference="";//date formatter as per the coder needSimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");//parse the string date-ti// me to Date objectDatestartDate=null;try{startDate=sdf.parse(date);}catch(ParseExceptione){e.printStackTrace();}//end date will be the current system time to calculate the lapse time difference//if needed, coder can add end date to whatever dateDateendDate=newDate();System.out.println(startDate);System.out.println(endDate);//get the time difference in millisecondslongduration=endDate.getTime()-startDate.getTime();//now we calculate the differences in different time units//this long value will be the total time difference in each unit//i.e; total difference in seconds, total difference in minutes etc...longdiffInSeconds=TimeUnit.MILLISECONDS.toSeconds(duration);longdiffInMinutes=TimeUnit.MILLISECONDS.toMinutes(duration);longdiffInHours=TimeUnit.MILLISECONDS.toHours(duration);longdiffInDays=TimeUnit.MILLISECONDS.toDays(duration);//now we create the time stamps depending on the value of each unit that we get//as we do not have the unit in years,//we will see if the days difference is more that 365 days, as 365 days = 1 yearif(diffInDays>365){//we get the year in integer not in float//ex- 791/365 = 2.167 in float but it will be 2 years in intintyear=(int)(diffInDays/365);timeDifference=year+" years ago";System.out.println(year+" years ago");}//if days are not enough to create year then get the dayselseif(diffInDays>1){timeDifference=diffInDays+" days ago";System.out.println(diffInDays+" days ago");}//if days value<1 then get the hourselseif(diffInHours>1){timeDifference=diffInHours+" hours ago";System.out.println(diffInHours+" hours ago");}//if hours value<1 then get the minuteselseif(diffInMinutes>1){timeDifference=diffInMinutes+" minutes ago";System.out.println(diffInMinutes+" minutes ago");}//if minutes value<1 then get the secondselseif(diffInSeconds>1){timeDifference=diffInSeconds+" seconds ago";System.out.println(diffInSeconds+" seconds ago");}returntimeDifference;// that's all. Happy Coding :)}
差值是12的倍数java中怎么写_如何在Java中找到两个日期之间的差值的持续时间?...
最新推荐文章于 2022-03-25 15:58:07 发布