2016-01-13 50 views
1

如何将c中的以下代码转换为ksh脚本。下面的代码会从年月日字符串中生成日期。然后将日期转换为一个长变量在unix shell ksh中将日期字符串转换为long

/* assemble date string */ 
sprintf(date_str,"%s%2s%s",year_str,month_str,day_str); 

/* convert to a long */ 
str2long((char *) date_str, 7, (long *) &long_date);  
+0

是从2015年1月1日的数值20150101您所需的输出? – David

+0

重新审视上面的例子后,它似乎没有得到值20150101。我无法理解所需的输出。任何帮助? – xGen

回答

0

如果你只是希望它转换为直长值,你可以用下面的函数做到这一点:

# Call with year month day 
# e.g. convert_date_to_long 2015 01 01 
function convert_date_to_long() { 
    date="${1}${2}${3}" 
    let long_date=$date 

    if [[ $long_date -gt 0 ]]; then 
     echo "Numeric date: ${long_date}" 
    fi 
} 

如果你不介意使用您的ksh脚本中的AWK语言,你想将其转换成一个划时代的时间戳,你可以用下面的函数做到这一点:

# Call with year month day 
# e.g. convert_date_to_epoch 2015 01 01 
function convert_date_to_epoch() { 
    awk -v year=${1} -v month=${2} -v day=${3} 'BEGIN { 
     agg_date = year " " month " " day " 00 00 00"; 
     utime = mktime(agg_date); 
     print utime; 
    }' 
}