Convert 2010-04-16 16:30:00 to “Tomorrow Afternoon”

后端 未结 4 1862
南旧
南旧 2020-12-19 22:08

Convert 2010-04-16 16:30:00 to \"Tomorrow Afternoon\" or convert another date to \"this afternoon\", \"next year\", \"next week wednesday\". You get the picture. Anyone know

4条回答
  •  半阙折子戏
    2020-12-19 23:14

    There might be more elegant solutions out there (look for Natural language formatting), but personally I couldn't find any.

    I would suggest calculating the distance from now to the date you're formatting, and using thresholds.

    Pseudo solution:

    diff = now - date
    
    if (diff < one_day) 
        format for today
    if (diff < two_days) 
        format for tomorrow
    if (diff < one_week)
        format using days from now
    .
    .
    .
    

    The comparison will work for both past and future dates, as long as you use compare with the abs value of diff. Display timeunit ago or timeunit from now by checking if diff is positive or negative.

    For the morning, afternoon, evening etc. you only need to check for the time of day in the date, and regarding the formatting type you hit, either display the time as numbers (far away), or natural language (recent or near date).

提交回复
热议问题