c#:
DateTime startDate = new DateTime(); DateTime endDate = new DateTime(); int age =0; int month = 0; int day = 0; if (endDate.Month>startDate.Month) { age = endDate.Year - startDate.Year; month = endDate.Month - startDate.Month; } else { age = endDate.Year - startDate.Year-1; month =12+ endDate.Month - startDate.Month; } if (endDate.Day>startDate.Day) { day = endDate.Day - startDate.Day; } else { //上个月天数-startDate.Day+endDate.Day day = (endDate-endDate.AddMonths(-1)).Days - startDate.Day+endDate.Day; month--; } Response.Write(string.Format("{0}岁{1}月{2}天", age, month, day));
php:
$age=0; $month=0; $day=0; $startDate=strtotime("2010-09-08 07:06:05"); $endDate=strtotime("2015-06-05 07:06:05"); if(date('n',$endDate)>date('n',$startDate)){ $age=date('Y',$endDate)-date('Y',$startDate); $month=date('n',$endDate)-date('n',$startDate); }else{ $age=date('Y',$endDate)-date('Y',$startDate)-1; $month=12+date('n',$endDate)-date('n',$startDate); } if(date('j',$endDate)>date('j',$startDate)){ $day = date('j',$endDate)-date('j',$startDate); }else{ $day= date('t',strtotime('-1 Month',$endDate))-date('j',$startDate)+date('j',$endDate); $month--; } echo sprintf('%s岁%s月%s天',$age,$month,$day);
java:
Calendar startDate = Calendar.getInstance(); startDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse("2010-09-08")); Calendar endDate = Calendar.getInstance(); endDate.setTime(new SimpleDateFormat("yyyy-MM-dd").parse("2010-10-5")); int age =0; int month = 0; int day = 0; if(endDate.get(Calendar.MONTH)>startDate.get(Calendar.MONTH)){ age = endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR); month = endDate.get(Calendar.MONTH)-startDate.get(Calendar.MONTH); }else{ age = endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR)-1; month =12+ endDate.get(Calendar.MONTH)-startDate.get(Calendar.MONTH); } if(endDate.get(Calendar.DAY_OF_MONTH)>startDate.get(Calendar.DAY_OF_MONTH)){ day = endDate.get(Calendar.DAY_OF_MONTH)-startDate.get(Calendar.DAY_OF_MONTH); }else{ Calendar preEndDate = Calendar.getInstance(); preEndDate.set(Calendar.YEAR, endDate.get(Calendar.YEAR)); preEndDate.set(Calendar.MONTH, endDate.get(Calendar.MONTH)-1); preEndDate.set(Calendar.DATE, 1); preEndDate.roll(Calendar.DATE, -1); int preMonthDays = preEndDate.get(Calendar.DATE); //获取endDay 上个月的天数 day =preMonthDays+endDate.get(Calendar.DAY_OF_MONTH)-startDate.get(Calendar.DAY_OF_MONTH); month--; } System.out.printf("%s岁%s月%s天",age,month,day);