求教date问题,谢谢

sylvan_lee 2008-03-13 12:19:39
准备用shell写一个实现时间格式转换的函数,
就是类似与date -d的功能
虽然date -d 可以实现大部分,但这对shell的版本有依赖
基本要求是:
2008/2/25 -> 2008-02-25 00:00:00
2008/2/25 22:33:44 -> 2008-02-25 22:33:44
2008/2/25 22:3:4 -> 2008-02-25 22:03:04
20080225 -> 2008-02-25 00:00:00
20080225223344 -> 2008-02-25 22:33:44
这种格式的转换需要考虑的事情太多了
哪位高人给点思路?谢谢

...全文
106 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
sylvan_lee 2008-03-18
  • 打赏
  • 举报
回复
好,谢谢楼上各位。matrix_ji 的思路和代码非常好,多谢了。
另外也谢谢参与的各位,不进行过度的设计。
就此结贴,来者有分。再谢。
core 2008-03-18
  • 打赏
  • 举报
回复
11楼思路还是蛮不错的,不过shell的效率有蛮大问题
liusujian02 2008-03-17
  • 打赏
  • 举报
回复
收藏了~
哆啦无梦 2008-03-16
  • 打赏
  • 举报
回复
不知道这个符不符和楼主的要求?
简单说一下思路:
1、把非数字的字符转成空格,然后把单个的数字进行前加0处理
2、把空格再去除之后,长度为8和14的两种格式自然是合法的依据相关的规则进行输出,否则输出错误信息


#!/bin/sh
format_date () {
# check argument
[ -z $1 ] && echo "usage: format_date <date-string>" && return
line="$@"

# format line
line=$(echo $line | sed 's/[^0-9]\+/ /g')
line=$(echo $line | sed 's/ \([0-9]\) / 0\1 /g')
line=$(echo $line | sed 's/^\([0-9]\) /0\1 /g')
line=$(echo $line | sed 's/ \([0-9]\)$/ 0\1/g')
line=$(echo $line | sed 's/ \+//g')
length=$(echo -n $line | wc -c)

if [ $length -eq 8 ] ; then
# format YYYY-MM-DD 00:00:00
year=$(echo $line | cut -c 1-4)
month=$(echo $line | cut -c 5-6)
day=$(echo $line | cut -c 7-8)
echo "$year-$month-$day 00:00:00"
elif [ $length -eq 14 ] ; then
# format YYYY-MM-DD HH:MM:SS
year=$(echo $line | cut -c 1-4)
month=$(echo $line | cut -c 5-6)
day=$(echo $line | cut -c 7-8)
hour=$(echo $line | cut -c 9-10)
min=$(echo $line | cut -c 11-12)
second=$(echo $line | cut -c 13-14)
echo "$year-$month-$day $hour:$min:$second"
else
echo "Invalid date string: $@"
fi
}


format_date 2008/2/25
format_date 2008/2/25 22:33:44
format_date 2008/2/25 22:3:4
format_date 20080225
format_date 20080225223344




执行结果 :

matrix@MMAC /c
$ sh test.sh
2008-02-02 00:00:00
2008-02-25 00:00:00
2008-02-25 22:33:44
2008-02-25 22:03:04
2008-02-25 00:00:00
2008-02-25 22:33:44
matrix@MMAC /c
$

:)Shell是很强大滴……


dxing_1983 2008-03-13
  • 打赏
  • 举报
回复
用asctime(xx)或ctime(xx)函数就行,不要用shell太麻烦了
dxing_1983 2008-03-13
  • 打赏
  • 举报
回复
用asctime(xx)或ctime(xx)函数就行,不要用shell太麻烦了
dxing_1983 2008-03-13
  • 打赏
  • 举报
回复
直接用ctime(xx)或asctime(xx)函数呀,用shell太麻烦了
dxing_1983 2008-03-13
  • 打赏
  • 举报
回复
直接用ctime(xx)或asctime(xx)函数呀,用shell太麻烦了
dxing_1983 2008-03-13
  • 打赏
  • 举报
回复
直接用ctime(xx)或asctime(xx)函数呀,用shell太麻烦了
dxing_1983 2008-03-13
  • 打赏
  • 举报
回复
哈哈,直接用asctime或ctime,就可以了。不要用shell
lbaby 2008-03-13
  • 打赏
  • 举报
回复
还有,够用就行,过度设计是不好的
lbaby 2008-03-13
  • 打赏
  • 举报
回复
对日期的处理向来是一个大麻烦,建议你用c完成一个专门的处理程序,
要加上 日期格式的参数,shell搞这个,只能把自己搞得头大
sylvan_lee 2008-03-13
  • 打赏
  • 举报
回复
恩,所有觉得没有很好的思路来写这个
cceczjxy 2008-03-13
  • 打赏
  • 举报
回复
这个估计很麻烦,只有尽量把可能的情况都设想到。

23,125

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧