Java中格林尼治时间和时间戳的相互转换
首先,将格林尼治时间转换为时间戳:
/**
* 格林尼治时间转换为时间戳
*/
public static long iso8601FormateTimeToLong(String time){
String formateTime = iso8601ToCustomerDate(time,"yyyy年M月d日 HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm:ss");
Date date = null;
try {
date = sdf.parse(formateTime);
} catch (ParseException e) {
MXLog.e(MXLog.APP_WARN, e);
}
return date.getTime();
}
然后是时间戳转为格林尼治时间:
/**
* 时间戳转成本机时区的格林尼治时间
* @param date
* @return
*/
public static String dateLongToiso8601(long date) {
DateTime dateTime = new DateTime(date);
return dateTime.toString("yyyy-MM-dd'T'HH:mm:ssZ");
}
根据时间戳判断距离当前时间的时间,和微信朋友圈中的时间类似,其实原理很简单,通过传入的时间和当前时间作比较即可:
/**
* 时间
* 1)0-1min 刚刚
* 2)1-60min xx分钟前,如3分钟前
* 3)1-24h xx小时前,如2小时前
* 4)昨天的 昨天+时+分,如,昨天 05:30
* 5)昨天之前的 月+日+时+分,如,1月3日 05:30
* 6)非本年 年+月+日+时+分,如2017年1月12日 05:30
*
* @param context
* @param time
* @return
*/
public static String formateTime3(Context context,long time){
boolean isTodayMessage = false;
Calendar todayBegin = Calendar.getInstance();
todayBegin.set(Calendar.HOUR_OF_DAY, 0);
todayBegin.set(Calendar.MINUTE, 0);
todayBegin.set(Calendar.SECOND, 0);
Calendar todayEnd = Calendar.getInstance();
todayEnd.set(Calendar.HOUR_OF_DAY, 23);
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
Calendar messageTime = Calendar.getInstance();
messageTime.setTime(new Date(time));
if (messageTime.before(todayEnd) && messageTime.after(todayBegin)) {
isTodayMessage = true;
}
SimpleDateFormat formatter = null;
int year = messageTime.get(Calendar.YEAR);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(new Date(System.currentTimeMillis()));
int currentYear = currentCalendar.get(Calendar.YEAR);
if (isTodayMessage) {
long currentTime = System.currentTimeMillis();
long duration = currentTime - time;
if (duration < 60 * 1000 && duration >= 0) {
//60s以内
return "刚刚";
} else if (duration >= 60 * 1000 && duration < 60 * 60 * 1000 ) {
//大于1分钟,小于1小时
return duration /60 /1000 + "分钟前";
} else if (duration >= 3600 * 1000 && duration < 3600 * 24 * 1000) {
//大于1小时
return duration / 3600 /1000 + "小时前";
}
}else if (isYesterday(time)){
formatter = new SimpleDateFormat("HH:mm");
return "昨天" + formatter.format(messageTime.getTime());
}else if (year != currentYear){
formatter = new SimpleDateFormat("yyyy年M月d日 HH:mm");
}else {
formatter = new SimpleDateFormat("M月d日 HH:mm");
}
if (formatter == null){
return "刚刚";
}else{
return formatter.format(messageTime.getTime());
}
}
还没有评论,来说两句吧...