【Java】java时间自动转成今天、昨天、前天,同年份则显示月日,不同年份将以年月日时显示

发布于:2021-09-17 11:49:44


最*做的功能发布的动态要求把时间自动转成今天、昨天、前天,如果是同一年刚显示月日,不同年的把年也显示,然后就有了以下工具类 -_-!! 话不多说直接上demo



import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
* Created with IntelliJ IDEA
* USER: Candy?LR(时间显示处理工具类)
* CLASSNAME: Mytest
* DATE: 2019/4/29
* TIME: 10:04
* JDK 1.8
*/
public class TimeProcessingUtil{

public static void main(String[] args) {
String dataStr = "2019-04-27 00:05";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
try {
Date ckDate = sdf.parse(dataStr);
System.out.println("原始时间为:" + dataStr);
System.out.println("转换后时间为:" + getTime(ckDate));
} catch (ParseException e) {
e.printStackTrace();
}
}

// 将传入时间与当前时间进行对比,是否今天昨天前天同一年
public static String getTime(Date date) {
boolean sameYear = false;
String todySDF = "HH:mm";
String yesterDaySDF = "昨天";
String beforYesterDaySDF = "前天";
String otherSDF = "MM-dd HH:mm";
String otherYearSDF = "yyyy-MM-dd HH:mm";
SimpleDateFormat sfd = null;
String time = "";
Calendar dateCalendar = Calendar.getInstance();
dateCalendar.setTime(date);
Date now = new Date();
Calendar todayCalendar = Calendar.getInstance();
todayCalendar.setTime(now);
todayCalendar.set(Calendar.HOUR_OF_DAY, 0);
todayCalendar.set(Calendar.MINUTE, 0);

if (dateCalendar.get(Calendar.YEAR) == todayCalendar.get(Calendar.YEAR)) {
sameYear = true;
} else {
sameYear = false;
}

if (dateCalendar.after(todayCalendar)) {// 判断是不是今天
sfd = new SimpleDateFormat(todySDF);
time = sfd.format(date);
return time;
} else {
todayCalendar.add(Calendar.DATE, -1);
if (dateCalendar.after(todayCalendar)) {// 判断是不是昨天
sfd = new SimpleDateFormat(todySDF);
time = yesterDaySDF + " " + sfd.format(date);

//time = yesterDaySDF;
return time;
}
todayCalendar.add(Calendar.DATE, -1);
if (dateCalendar.after(todayCalendar)) {// 判断是不是前天

sfd = new SimpleDateFormat(todySDF);
time = beforYesterDaySDF + " " + sfd.format(date);
//time = beforYesterDaySDF;
return time;
}
}

if (sameYear) {
sfd = new SimpleDateFormat(otherSDF);
time = sfd.format(date);
} else {
sfd = new SimpleDateFormat(otherYearSDF);
time = sfd.format(date);
}

return time;
}
}


结果展示如图下所示:

相关推荐

最新更新

猜你喜欢