2011-02-04 120 views
3

我在過去兩天編寫了CS 462 Office Hours應用程序。 most recent iteration告訴用戶何時下一個辦公時間時間塊。現在,它只是格式化爲「週四(2月3日)下午3點。」不過,我希望它有點聰明,並且說「今天下午三點」或「明天上午十點」。時間戳的相對格式化

這類似於推特上的Twitter相對時間戳(它表示「3分鐘前」或「23小時前;」之外,它列出日期)。但就我而言,這將是相反的,因爲我們正在處理未來的時間。

基本上,它需要足夠聰明才能知道事件是今天還是明天。除此之外,我只想顯示一週中的日期和日期。

有沒有辦法與KRL做到這一點?我是否只需要使用邏輯like this並編寫函數(或模塊)?

回答

2

這是我具備的功能:

// First define some constants to measuring relative time 
now = time:now({"tz": "America/Denver"}); 
midnight = time:new("23:59:59.000-07:00"); 
tomorrow_midnight = time:add(midnight, {"days": 1}); 
yesterday_midnight = time:add(midnight, {"days": -1}); 

// Functions for calculating relative time 
relativefuturedate = function(d){ 
    ispast(d) => "today (past) at " + justtime(d) 
    | istoday(d) => "today at " + justtime(d) 
    | istomorrow(d) => "tomorrow at " + justtime(d) 
    | datetime(d); 
}; 

istoday = function(d){ 
    d > now && d <= midnight; 
}; 

istomorrow = function(d){ 
    not istoday(d) && d <= tomorrow_midnight; 
}; 

ispast = function(d){ 
    d < now; 
}; 

isfuture = function(d){ 
    d > now; 
}; 

justtime = function(d){ 
    time:strftime(d, "%l:%M %p"); 
}; 

datetime = function(d){ 
    time:strftime(d, "%A (%B %e) at %l:%M %p"); 
}; 

這應該做的伎倆。現在我用這個規則測試它:

rule first_rule { 
    select when pageview ".*" 
    pre { 
    today_9 = time:new("2011-02-09T09:00:00.000-07:00"); 
    today_12 = time:new("2011-02-09T12:00:00.000-07:00"); 
    today_4 = time:new("2011-02-09T16:00:00.000-07:00"); 
    tomorrow_9 = time:new("2011-02-10T09:00:00.000-07:00"); 
    tomorrow_4 = time:new("2011-02-10T16:00:00.000-07:00"); 
    nextday_9 = time:new("2011-02-11T09:00:00.000-07:00"); 

    relative_now = relativefuturedate(now); 
    relative_today_9 = relativefuturedate(today_9); 
    relative_today_12 = relativefuturedate(today_12); 
    relative_today_4 = relativefuturedate(today_4); 
    relative_tomorrow_9 = relativefuturedate(tomorrow_9); 
    relative_tomorrow_4 = relativefuturedate(tomorrow_4); 
    relative_nextday_9 = relativefuturedate(nextday_9); 

    message = << 
     Now: #{relative_now}<br /> 
     Today at 9: #{relative_today_9}<br /> 
     Today at 12: #{relative_today_12}<br /> 
     Today at 4: #{relative_today_4}<br /> 
     Tomorrow at 9: #{relative_tomorrow_9}<br /> 
     Tomorrow at 4: #{relative_tomorrow_4}<br /> 
     Day after tomorrow at 9: #{relative_nextday_9}<br /> 
    >>; 
    } 
    notify("Time calculations:", message) with sticky=true; 
} 

但是,這似乎還沒有工作。我得到這樣的輸出:

Incorrect relative times

有人能看到有什麼不對?

1

目前在KRL中沒有內置功能來完成此操作。你可能需要編寫一個函數或模塊來做到這一點,我很樂意看到它,如果/當你這樣做。

+0

我一直在努力,但還沒有完成。我完成後會在這裏發佈。 – 2011-02-07 17:00:10