使用方式(需先创建下面工具类)
DateTime.getTime("2019-05-06 12:23:08");
效果:
如果是刚收到返回:刚刚
在当前小时内,返回,几分钟前
在今天内,不在当前小时,返回:凌晨/早上/上午/中文/下午/傍晚/晚上+时间
在本月内,昨天返回:昨天
在本年中,不在今天不在昨天返回:几月几日
不在本年返回:年/月/日
工具类:DateTime
import java.util.Calendar;
/**
* 把日期改为上午几点,下午几点
* @author XHB
* @date
*/
public class DateTime {
public static void main(String[] args) {
System.out.println(getTime("2019-05-06 12:23:08"));
}
/**
* 使用方法·传入String类型
* @param dt
* @return
*/
public static String getTime(String dt) {
//拆分传来的日期,获取详细数值
int year = 0;//年份
int month = 0;//月份
int day = 0;//日
int hour = 0;//小时
int minute = 0;//分
int second = 0;//秒
String str[] = dt.split(" ");
for (int i = 0; i < str.length; i++) {
String str1[] = str[0].split("-");
for (int j = 0; j < str1.length; j++) {
year = Integer.valueOf(str1[0]);
month = Integer.valueOf(str1[1]);
day = Integer.valueOf(str1[2]);
}
String str2[] = str[1].split(":");
for (int j = 0; j < str2.length; j++) {
hour = Integer.valueOf(str2[0]);
minute = Integer.valueOf(str2[1]);
second = Integer.valueOf(str2[2]);
}
break;
}
//获取当前时间
Calendar cal = Calendar.getInstance();
int years = cal.get(Calendar.YEAR);//获取年份
int months = cal.get(Calendar.MONTH) + 1;//获取月份 ,这里需要需要月份的范围为0~11,因此获取月份的时候需要+1才是当前月份值
int days = cal.get(Calendar.DATE);//获取日
int hours = cal.get(Calendar.HOUR_OF_DAY);//小时 //Calendar.HOUR是12小时制
int minutes = cal.get(Calendar.MINUTE);//分
int seconds = cal.get(Calendar.SECOND);//秒
int WeekOfYears = cal.get(Calendar.DAY_OF_WEEK);//一周的第几天,英语国家星期从星期日开始计算
//比较是不是今天
if (year == years && month == months && day == days) {
//如果是今天,验证是不是同一个小时
if (hour == hours) {
//验证是不是同一分钟
if (minute == minutes || (minutes-minute) == 1) {
//是同一分钟,返回刚刚
return "刚刚";
}else{
return (minutes-minute) + "分钟前";
}
}else{
String strMinute = "";
if(minute < 10){
strMinute = "0" + minute;
}else{
strMinute = "" + minute;
}
//验证时区
if (hour <= 6) {//7点之前
return "凌晨 "+ hour + ":" + strMinute ;
}
if (hour > 6 && hour <= 8) {//7-9点
return "早上 "+ hour + ":" + strMinute ;
}
if (hour > 8 && hour <= 11) {//9-12点
return "上午 "+ hour + ":" + strMinute ;
}
if (hour > 11 && hour <= 12) {//12点
return "中午 "+ hour + ":" + strMinute ;
}
if (hour > 12 && hour <= 17) {//14-18点
return "下午 "+ hour + ":" + strMinute ;
}
if (hour > 17 && hour <= 19) {//19-20点
return "傍晚 "+ hour + ":" + strMinute ;
}
if (hour > 19 ) {//20以后
return "晚上 "+ hour + ":" + strMinute ;
}
}
//比较是不是昨天
}else if (year == years && month == months && (days-day) == 1) {
return "昨天";
//比较是不是今年
}else if (year == years) {
return month+"月"+day+"日";
}else{
return year+"/"+month+"/"+day;
}
return " ";
}
}