关于时间显示为今天、昨天、星期一之类的格式问题

来源:互联网 发布:淘宝活动页面代码 编辑:程序博客网 时间:2024/06/06 05:55

时间格式统一用年月日判断yyyy-MM-dd,因为时分秒处理起来有些识别上的问题,如 第一个时间是 2016-03-02 22:00::00  第二个时间为  2016-03-03 8:00::00 

第一个时间相对于第二个时间是昨天还是今天?

下面是代码:

/**
 * 将时间转化为本地星期
 * @author Administrator
 *
 */
public class DateTest1 {
public static void main(String[] args) throws ParseException {
String currentTime = String.format("%tF%n", new Date(System.currentTimeMillis()));
System.out.println("当前时间:"+currentTime);
String result = getDayDiff("2016-02-28", currentTime);
System.out.println("显示的时间格式:"+result);
}
/**
* 得到时间差 yyyy-MM-dd 格式
* @param time
* @return
* @throws ParseException
*/
public static String getDayDiff(String time) throws ParseException{
String currentTime = String.format("%tF%n", new Date(System.currentTimeMillis()));
return getDayDiff(time, currentTime);
}
/**
* 得到时间差 yyyy-MM-dd 格式
* @param fDateStr 需要计算的时间
* @param oDateStr 应该传入当前时间
* @return 
* @throws ParseException
*/
public static String getDayDiff(String fDateStr, String oDateStr) throws ParseException{
int result = daysOfTwo(fDateStr, oDateStr);
String timeResult = "";
switch (result) {
case -1:
timeResult = "请检查时间";
break;
case 0:
timeResult = "今天";
break;
case 1:
timeResult = "昨天";
break;


default:
timeResult = String.format("%tA%n", getDateFormat(fDateStr));
break;
}
if(Math.abs(result) > 7){//假如时间大于7天
timeResult = fDateStr;
}
return timeResult;
}
/**
* 判断时间相差几天
* @param fDate yyyy-MM-dd 格式
* @param oDate 应写当前时间
* @return 时间为-1时,请检查代码
* @throws ParseException 
*/
public static int daysOfTwo(String fDateStr, String oDateStr) throws ParseException {
Date fDate = getDateFormat(fDateStr);
Date oDate = getDateFormat(oDateStr);
Calendar aCalendar = Calendar.getInstance();
aCalendar.setTime(fDate);
int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
aCalendar.setTime(oDate);
int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
return day2 - day1;
}


/**
* 将时间转换为 Date类型
* @param time yyyy-MM-dd格式
* @return
* @throws ParseException 
*/
public static Date getDateFormat(String time) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(time);
}


}

0 0
原创粉丝点击