javascript和PHP及MYSQL时间格式化函数
1、javascript:
/** * 友好的时间显示 * @param int sTime 待显示的时间 */ function friendlyDate(sTime) { if (!sTime) return '—' var dur = 1000 sTime = sTime * dur var cTime = parseInt(new Date().getTime().toString()) var dTime = cTime - sTime var dDay = parseInt(new Date().getUTCDate()) - parseInt(new Date(sTime).getUTCDate()) var dYear = parseInt(new Date().getUTCFullYear()) - parseInt(new Date(sTime).getUTCFullYear()) var month = parseInt(new Date(sTime).getUTCMonth())+1 var day = new Date(sTime).getUTCDate() var hour = new Date(sTime).getUTCHours() var minute = new Date(sTime).getUTCMinutes() if(month<10){ month = "0"+month } if(day<10){ day = "0"+day } if(hour<10){ hour = "0"+hour } if(minute<10){ minute = "0"+minute } if(dTime>0){ if( dTime < 60 * dur ){ if(dTime < 10 * dur){ return '刚刚' }else{ return parseInt(Math.floor(dTime / 10) * 10 / dur)+"秒前" } }else if( dTime < 3600 * dur ){ return parseInt(dTime/60/dur)+"分钟前" }else if( dYear==0 && dDay == 0 ){ return '今天'+hour+':'+minute }else if(dYear==0){ return month+'月'+day+'日 '+hour+':'+minute }else{ return new Date(sTime).getUTCFullYear()+'-'+month+'-'+day+' '+hour+':'+minute } }else{ return new Date(sTime).getUTCFullYear()+'年'+month+'月'+day+'日 '+hour+':'+minute } } var time = friendlyDate(1525774541) console.log(time)
2、PHP:
function friendlyDate($sTime) { if (!$sTime) return '—'; $cTime = time(); $dTime = $cTime - $sTime; $dDay = intval(date("z",$cTime)) - intval(date("z",$sTime)); $dYear = intval(date("Y",$cTime)) - intval(date("Y",$sTime)); if($dTime>0){ if( $dTime < 60 ){ if($dTime < 10){ return '刚刚'; }else{ return intval(floor($dTime / 10) * 10)."秒前"; } }elseif( $dTime < 3600 ){ return intval($dTime/60)."分钟前"; }elseif( $dYear==0 && $dDay == 0 ){ return '今天'.date('H:i',$sTime); }elseif($dYear==0){ return date("m月d日 H:i",$sTime); }else{ return date("Y-m-d H:i",$sTime); } }else{ return date("Y年m月d日 H:i",$sTime); } }
3、mysql:
DELIMITER // CREATE FUNCTION friendlyDate(sTime char(11)) RETURNS char(11) BEGIN if sTime='' then return '-'; end if; set @cTime=UNIX_TIMESTAMP(); set @dTime=@cTime-sTime; set @dDay=DATE_FORMAT(@cTime,'%e')-DATE_FORMAT(@sTime,'%e'); set @dYear=DATE_FORMAT(@cTime,'%Y')-DATE_FORMAT(@sTime,'%Y'); if @dTime>0 then if @dTime<60 then if @dTime<10 then return '刚刚'; else set @t=floor(@dTime/10)*10; set @ret=concat(@t,'秒前'); return @ret; end if; elseif @dTime<3600 then set @t=@dTime/60; set @ret=concat(@t,'分钟前'); return @ret; elseif @dYear=0 && @dDay=0 then set @t=DATE_FORMAT(@sTime,'%H:%i'); set @ret=concat('今天',@t); return @ret; elseif @dYear=0 then return DATE_FORMAT(@sTime,'%m月%d日 %H:%i'); else return DATE_FORMAT(@sTime,'%Y-%m-%d %H:%i:%s'); end if; else return DATE_FORMAT(@sTime,'%Y年%m月%d日 %H:%i'); end if; END // DELIMITER ;
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦