mysql yu日期_帮助类解决日期时间问题(包含从Mysql中查出来的数据后面多了个0的问题,以友好的方式显示时间的问题) | 学步园...

在做项目的时候,总是离不开日期时间这个问题,遇到的多了也总结出来一些常用的方法,将其抽出类,合成一个工具类,如下:

重点:

1.以友好的方式显示时间:几天前啦,几小时前啦,几分钟前啦等等

效果如下:

0_1306161191JJ9U.gif

/**

* 以友好的方式显示时间

* @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的问题

图:

0_1306161771FRPQ.gif

只要用这个方法将查出来的时间转化一下就好了

/**

* 格式化字符串,解决从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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值