在做项目的时候,总是离不开日期时间这个问题,遇到的多了也总结出来一些常用的方法,将其抽出类,合成一个工具类,如下:
重点:
1.以友好的方式显示时间:几天前啦,几小时前啦,几分钟前啦等等
效果如下:
/**
* 以友好的方式显示时间
* @param time
* @return
*/
public static String friendlyTime(Date time) {
//获取time距离当前的秒数
int ct = (int)((System.currentTimeMillis() - time.getTime())/1000);
if(ct == 0) {
return "刚刚";
}
if(ct > 0 && ct < 60) {
return ct + "秒前";
}
if(ct >= 60 && ct < 3600) {
return Math.max(ct / 60,1) + "分钟前";
}
if(ct >= 3600 && ct < 86400)
return ct / 3600 + "小时前";
if(ct >= 86400 && ct < 2592000){ //86400 * 30
int day = ct / 86400 ;
return day + "天前";
}
if(ct >= 2592000 && ct < 31104000) { //86400 * 30
return ct / 2592000 + "月前";
}
return ct / 31104000 + "年前";
}
用的时候只需要调用这个方法即可:
//以友好的方式显示时间
for(Post p:postlist){
p.setCreateTime(DateUtil.friendlyTime(DateUtil.stringToDate(p.getCreateTime())));
}
2格式化字符串,解决从MySql中查出来的数据后面多了0的问题
图:
只要用这个方法将查出来的时间转化一下就好了
/**
* 格式化字符串,解决从MySql中查出来的数据后面多了0的问题
* @param date
* @return
*/
public static String formatDate(Date date){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
这些东西呢,方法没什么高深的东西,但却很实用
为了大家方便,贴出整个类的代码来,将其保存为DateUtil.java,其它的就不多说了,类里面有
package com.h.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*有关日期时间处理的一些方法
* @author Yu
*
*/
public class DateUtil {
/**
* 获取当前时间
* @return当前的时间
*/
public static String getNow(){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
/**
* 以友好的方式显示时间
* @param time
* @return
*/
public static String friendlyTime(Date time) {
//获取time距离当前的秒数
int ct = (int)((System.currentTimeMillis() - time.getTime())/1000);
if(ct == 0) {
return "刚刚";
}
if(ct > 0 && ct < 60) {
return ct + "秒前";
}
if(ct >= 60 && ct < 3600) {
return Math.max(ct / 60,1) + "分钟前";
}
if(ct >= 3600 && ct < 86400)
return ct / 3600 + "小时前";
if(ct >= 86400 && ct < 2592000){ //86400 * 30
int day = ct / 86400 ;
return day + "天前";
}
if(ct >= 2592000 && ct < 31104000) { //86400 * 30
return ct / 2592000 + "月前";
}
return ct / 31104000 + "年前";
}
/**
* 将字符串转换为Date类型
* @param str
* @return
*/
public static Date stringToDate(String str) {
try {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 格式化字符串,解决从MySql中查出来的数据后面多了0的问题
* @param date
* @return
*/
public static String formatDate(Date date){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
}
}