出生年月日,轉化爲 -> 年齡 (java)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;



/** 將出生年月日按當前日期值(如:19890921)轉化爲年齡 */
@SuppressLint("SimpleDateFormat") 
public int getAge(String brithday)
{
	int age = 0;
	
	try
	{
		// 對輸入的生日格式 規整化爲8位字符串形式
		brithday = brithday.trim().replace("-", "").replace(" ", "").replace("_", "").replace("/", "").replace("\\", "").substring(0, 8);
		
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Date birthDay = format.parse(brithday);
		long birthL = birthDay.getTime();	// 生日對應的毫秒時間值
		
		Date now = new Date();
		long nowL = now.getTime();			// 當前日期對應的毫秒時間值
		
		if(nowL > birthL) age = (int) ((nowL - birthL) / 1000 / 60 / 60 / 24 / 365);	// 時間差轉化爲年取整
	}
	catch (ParseException e)
	{
		e.printStackTrace();
	}
	
	return age;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章