android 时间的格式化问题

android中经常遇到要格式化时间,下面记录一下"yyyy-MM-dd”类型和  ”kk:mm:ss”类型的时间格式化方法:

static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//只取年--月--日

	public static int diffDays(String compareTime) {
		Calendar now = Calendar.getInstance();
		try {
			Date today = dateFormat.parse(dateFormat.format(now.getTime()));
			Date compareDate = dateFormat.parse(compareTime);
			return (int) ((compareDate.getTime() - today.getTime()) / 86400000);
		} catch (ParseException e) {
			e.printStackTrace();
			return 0;
		}
	}

	static SimpleDateFormat timeFormatter = new SimpleDateFormat(
			"yyyy-MM-dd kk:mm:ss");
	public static String testErrorTime(String compareTime) {
		try{
			int diff = diffDays(compareTime);
			if (diff == 0) {
				Date date= timeFormatter.parse(compareTime);
				return DateFormat.format("kk:mm:ss", date.getTime()).toString();//取 时--分--秒
			} else {
				Date date;
				date = dateFormat.parse(compareTime);
				return dateFormat.format(date);  //取  年--月--日
			}
		}catch(ParseException e){
			e.printStackTrace();
			return "00:00:00";
		}
	}

你可能感兴趣的:(android 时间的格式化问题)