那些和日期息息相关的方法

在平时的开发中,我们经常会和日期和时间打交道,想必大家多少都使用到了和日期有关的工具类,最常见的比如日期格式转化等。以下我将会整理一些和日期息息相关的例子和通用方法。

1. 今天?昨天?前天?

例子:
图片1

这里将一个普通的日期转化成较为友好的“今天”、“昨天”、“前天”,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static String FriendlyDate(Date compareDate) {
Date nowDate = new Date();
int dayDiff = daysOfTwo(nowDate, compareDate);
if (dayDiff <= 0) {
return "今天";
} else if (dayDiff == 1) {
return "昨天";
} else if (dayDiff == 2) {
return "前天";
} else {
return new SimpleDateFormat("M月d日 E").format(compareDate);
}
}
public static int daysOfTwo(Date originalDate, Date compareDateDate) {
Calendar aCalendar = Calendar.getInstance();
aCalendar.setTime(originalDate);
int originalDay = aCalendar.get(Calendar.DAY_OF_YEAR);
aCalendar.setTime(compareDateDate);
int compareDay = aCalendar.get(Calendar.DAY_OF_YEAR);
return originalDay - compareDay;
}

2. 时间戳友好化

有时候我们是用时间戳来存储时间的,在Java中时间戳是一个占有13位数字的long型整数,比如1481687708985,
当前时间戳的获取方式如下:

1
2
3
Timestamp now = new Timestamp(System.currentTimeMillis());
long time = now.getTime();
System.out.print("The Timestamp is : " + time);

或者

1
2
3
Date date = new Date();
long time = date.getTime();
System.out.print("The Timestamp is : " + time);

特定日期的时间戳:

1
2
3
4
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2017-01-25 10:20:30"); //此处需要需要try/catch
long time = date.getTime();
System.out.print("The Timestamp is : " + time);

把时间戳转化为日期时间:

1
2
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = fm.format(timestamp);

例子:
图片2

正如图片所示,从数据库中读出的每一个时间戳都被友好化地进行了展示,关键代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static String friendlyDaysAgo(long time) {
String agoStr = "";
Timestamp now = new Timestamp(System.currentTimeMillis());
long interval = now.getTime() - time;
long d = interval/(1000*60*60*24);
if (interval <= 3*60*1000) { //间隔在3分钟以内
agoStr += "刚刚";
return agoStr;
}
if (d == 0) {
agoStr += "今天";
} else if (d > 0) {
if (d >= 30) {
agoStr += (d/30 + "个月前");
} else if (d == 1) {
agoStr += ("昨天");
} else {
agoStr += (d + "天前");
}
} else {
agoStr += ("时间已超过当前");
}
return agoStr;
}

致转载者:请遵循CC-BY-NC-ND协议。