title: 那些和日期息息相关的方法
date: 2017-01-24 21:01:06
tags:
在平时的开发中,我们经常会和日期和时间打交道,想必大家多少都使用到了和日期有关的工具类,最常见的比如日期格式转化等。以下我将会整理一些和日期息息相关的例子和通用方法。
####1. 今天?昨天?前天?
例子:

这里将一个普通的日期转化成较为友好的“今天”、“昨天”、“前天”,代码如下:
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, 当前时间戳的获取方式如下:
Timestamp now = new Timestamp(System.currentTimeMillis());
long time = now.getTime();
System.out.print("The Timestamp is : " + time);
或者
Date date = new Date();
long time = date.getTime();
System.out.print("The Timestamp is : " + time);
特定日期的时间戳:
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);
把时间戳转化为日期时间:
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = fm.format(timestamp);
例子:
public static String friendlyDaysAgo(long date) {
String agoStr = "";
Timestamp now = new Timestamp(System.currentTimeMillis());
long interval = now.getTime() - date;
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;
}
2440

被折叠的 条评论
为什么被折叠?



