`

TimeDifference.js获取时间差插件

 
阅读更多
http://www.oschina.net/p/timedifference

/** Created by postbird on 2016/4/1.  ...*/
/**

 *      @postbird

 *      1、本插件采用js编写,可直接将函数复制到个人js文件,减少get请求数

 *      2、author:powered by postbird

 *      3、email: ptbird@yeah.net

 *      4、site:http://www.ptbird.cn

 *      5、license : MIT

 * */
/**

 *  函数使用说明:

 *      1、直接调用函数  TimeDifference()

 *          返回说明: 返回距离当前的时间差

 * */
function timeDifference(tmpTime) {
    var mm=1000;//1000毫秒 代表1秒

    var minute = mm * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var month = day * 30;
    var ansTimeDifference=0;//记录时间差

    var tmpTimeStamp = tmpTime ? Date.parse(tmpTime.replace(/-/gi, "/")) : new Date().getTime();//将 yyyy-mm-dd H:m:s 进行正则匹配

    var nowTime = new Date().getTime();//获取当前时间戳

    var tmpTimeDifference = nowTime - tmpTimeStamp;//计算当前与需要计算的时间的时间戳的差值

    if (tmpTimeDifference < 0) {                //时间超出,不能计算

        alert("开始日期大于结束日期,计算失败!");
        return 0;
    }
    /**

     * 通过最开始强调的各个时间段用毫秒表示的数值,进行时间上的取整,为0的话,则没有到达

     * */
    var DifferebceMonth = tmpTimeDifference / month;    //进行月份取整

    var DifferebceWeek = tmpTimeDifference / (7 * day);//进行周取整

    var DifferebceDay = tmpTimeDifference / day;//进行天取整

    var DifferebceHour = tmpTimeDifference / hour;//进行小时取整

    var DifferebceMinute = tmpTimeDifference / minute;//进行分钟取整

    if (DifferebceMonth >= 1) {
        return tmpTime;                 //大于一个月 直接返回时间

    } else if (DifferebceWeek >= 1) {
        ansTimeDifference= parseInt(DifferebceWeek) + "个星期前";
    } else if (DifferebceDay >= 1) {
        ansTimeDifference = parseInt(DifferebceDay) + "天前";
    } else if (DifferebceHour >= 1) {
        ansTimeDifference = parseInt(DifferebceHour) + "个小时前";
    } else if (DifferebceMinute >= 1) {
        ansTimeDifference = parseInt(DifferebceMinute) + "分钟前";
    } else {
        ansTimeDifference = "刚刚";
    }
    return ansTimeDifference;
}
分享到:
评论

相关推荐

    javascript时间差插件分享_.docx

    根据提供的文档信息,本文将详细解析“javascript时间差插件”的功能、实现原理及使用方法。 ### 插件概述 该插件名为“TimeDifference.js”,主要用途是计算指定时间与当前时间之间的差异,并以人性化的语言展示...

    javascript时间差插件分享

    JavaScript时间差插件是一种用于计算两个时间点之间差值的工具,它可以帮助开发者在Web应用中轻松地展示如“x分钟前”、“y天后”等时间信息。在这个实例中,我们看到一个简单的HTML页面结合了一个名为`Time...

    javasctipt如何显示几分钟前、几天前等.docx

    ### JavaScript 如何显示几分钟前、几天前等时间差方法详解 #### 标题与描述解析: 标题和描述都提到了“JavaScript如何显示几分钟前、几天前等”。这明确指向了一个功能性的需求——即如何在前端使用JavaScript...

    jQuery将时间转换为几天前代码.zip

    在JavaScript编程领域,日期和时间的处理是常见的需求,特别是在前端开发中,如网页动态展示信息的更新时间。jQuery是一个广泛使用的JavaScript库,它提供了一系列方便的API来简化DOM操作和事件处理。在这个"jQuery...

    jQuery将时间转换为几天前特效代码

    在JavaScript和前端开发中,jQuery库经常被用来增强DOM操作和事件处理,同时它也提供了丰富的插件和方法来处理各种复杂的需求。标题中的“jQuery将时间转换为几天前特效代码”是一个实用的功能,用于将特定的时间戳...

Global site tag (gtag.js) - Google Analytics