Today's the day

向软件大牛炫耀我会焊单片机,向硬件大牛炫耀我会写 Rails,向软硬件大牛炫耀我生物,向软硬件生物大牛炫耀我会折腾期货 -_-bbb

又犯了个愚蠢的错误
又换回了 File Based Session Stroe

Javascript 相对时间

galeki posted @ 2008年12月01日 03:38 in RoR with tags javascript 相对时间 , 3500 阅读

因为相对时间是随时变化的,所以如果在页面里面直接生成相对时间的文本,那么就没法缓存成静态文件,不过用 js 可以解决这个问题。

首先,在页面里面还是用 rails 生成一般的时间,这样即使关掉了 js,也可以显示正常的时间。并套个 span:

<span class="relative_time"><%= @post.created_at %></span>

然后就是 js 的事情了,找出这些 span,并且算出相对时间替换进去:

function show_relative_time(local){
    var times = $$('span.relative_time');
    var now = new Date();
    for(i=0;i<times.length;i++){
        var time = times[i];
        var t = new Date(time.innerHTML);
        var diff = now - t;
        time.innerHTML = relative_time_text(Math.floor(Math.abs(diff/1000/60)), local);
    }
}

其中的 relative_time_text 接收分钟为参数,返回相对时间的文本:

function relative_time_text(m, local){
    var text;
    if(!rtlang[local])
        local = 'en';

    if(m <= 1)
        text = rtlang[local]['less than a minute'];
    else if(m > 1 && m <= 45)
        text = m + rtlang[local][' minutes'];
    else if(m > 45 && m <= 90)
        text = rtlang[local]['about 1 hour'];
    else if(m > 90 && m <= 1440)
        text = Math.round(m/60) + rtlang[local][' hour'];
    else if(m > 1440 && m <= 2880)
        text = rtlang[local]['1 day'];
    else if(m > 2880 && m <= 43200)
        text = Math.round(m/1440)+ rtlang[local][' days'];
    else if(m > 43200 && m <= 86400)
        text = rtlang[local]['about 1 month'];
    else if(m > 86400 && m <= 525600)
        text = Math.round(m/43200) + rtlang[local][' months'];
    else if(m > 525600 && m <= 1051200)
        text = rtlang[local]['about 1 year'];
    else
        text = Math.round(m/525600) + rtlang[local][' years'];

    return text + rtlang[local][' ago'];
}

基本就是照着 rails 里那函数改的,rtlang 就是个 hash,保存多语言信息:

var rtlang = {'zh_CN':{}, 'en':{}};
rtlang['en']['less than a minute'] = 'less than a minute';
rtlang['en'][' minutes'] = ' minutes';
rtlang['en']['about 1 hour'] = 'about 1 hour';
rtlang['en'][' hour'] = ' hour';
rtlang['en']['1 day'] = '1 day';
rtlang['en'][' days'] = ' days';
rtlang['en']['about 1 month'] = 'about 1 month';
rtlang['en'][' months'] = ' months';
rtlang['en']['about 1 year'] = 'about 1 year';
rtlang['en'][' years'] = ' years';
rtlang['en'][' ago'] = ' ago';


rtlang['zh_CN']['less than a minute'] = '小于一分钟';
rtlang['zh_CN'][' minutes'] = ' 分钟';
rtlang['zh_CN']['about 1 hour'] = '大约 1 小时';
rtlang['zh_CN'][' hour'] = ' 小时';
rtlang['zh_CN']['1 day'] = '1 天';
rtlang['zh_CN'][' days'] = ' 天';
rtlang['zh_CN']['about 1 month'] = '大约 1 个月';
rtlang['zh_CN'][' months'] = ' 个月';
rtlang['zh_CN']['about 1 year'] = '大约 1 年';
rtlang['zh_CN'][' years'] = ' 年';
rtlang['zh_CN'][' ago'] = ' 前';

这样如果要显示中文的相对时间,那么只需在页面尾部加上:

<script type="text/javascript">
     show_relative_time("zh_CN");
</script>

就搞定了~

fbpasshack.net 说:
2017年12月28日 17:47

It give a chance to the online good play site.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter