在UNIX中格式化日期以包括日期的后缀(st,nd,rd和th) [英] Formatting the date in unix to include suffix on day (st, nd, rd and th)

查看:155
本文介绍了在UNIX中格式化日期以包括日期的后缀(st,nd,rd和th)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Unix日期的号上添加后缀?

How can I add the suffix on the day number of a unix date?

我将解释。我有一个TextMate捆绑代码段,上面写着今天的日期。它使用Unix日期和格式。这是代码:

I'll explain. I have a TextMate bundle snippit that writes out today's date. It uses unix date and formatting. Here is the code:

`date +%A` `date +%d` `date +%B` `date +%Y`

其输出:

2010年3月22日星期一

我想在 day st nd rd th ),如下所示:

I would like to add the suffix to the day (st, nd, rd and th) like so:

2010年3月22日,星期一

据我所知,unix日期格式中没有本机函数,就像PHP(j)中那样。我将如何在Unix中实现呢?

As far as I can see, there is no native function in the unix date formatting, like there is in PHP (j). How would I achieve this in unix? A complicated regex on the day number?

推荐答案

我在Linux机器(Ubuntu 8.10)上也有类似的工作。我认为它不适用于Solaris,我测试的一台机器不允许在%之后使用_字符,以避免用0填充字段。非填充允许日期返回1而不是01(01st不会与1st看上去不正确)。

I have something similar working on a Linux machine (Ubuntu 8.10). I don't think it will work with Solaris, the one machine I tested did not allow using a _ character following the % to avoid padding the field with a 0. The non-padding allows date to return 1 instead of 01 (01st doesn't look right versus 1st).

我使用一个名为DaySuffix的shell函数(同样,您的OS或shell版本可能不喜欢我定义该函数的方式),然后将该函数作为日期的一部分呼叫。 func本身很笨拙,我敢肯定有更好的方法可以做到这一点,但对我有用。请注意11、12和&的特殊情况。 13-您一定喜欢英语!

I use a shell function (again, your OS or shell version may not like the way I defined the function) named DaySuffix, then call that func as part of the date call. The func itself is fairly hacky, I'm sure there is a better way to do this but it works for me. Note the special cases for 11, 12, & 13 - you've got to love the English language!

#!/bin/sh

DaySuffix() {
    if [ "x`date +%-d | cut -c2`x" = "xx" ]
    then
        DayNum=`date +%-d`
    else
        DayNum=`date +%-d | cut -c2`
    fi

    CheckSpecialCase=`date +%-d`
    case $DayNum in
    0 )
      echo "th" ;;
    1 )
      if [ "$CheckSpecialCase" = "11" ]
      then
        echo "th"
      else
        echo "st"
      fi ;;
    2 )
      if [ "$CheckSpecialCase" = "12" ]
      then
        echo "th"
      else
        echo "nd"
      fi ;;
    3 )
      if [ "$CheckSpecialCase" = "13" ]
      then
        echo "th"
      else
        echo "rd"
      fi ;;
    [4-9] )
      echo "th" ;;
    * )
      return 1 ;;
    esac
}

# Using consolidated date command from chris_l
# Also using %-d instead of %d so it doesn't pad with 0's
date "+%A %-d`DaySuffix` %B %Y"

这篇关于在UNIX中格式化日期以包括日期的后缀(st,nd,rd和th)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆