简体   繁体   中英

Convert date stored variable into unix time BASH

I'm trying to convert a date stored in a variable into unix timestamp. I have the value, I must provide the format of this value("%m%d%Y") and then convert it ("%s"). Could you please give me a hint?

>initial_date=02012014
>date_2_unixtime=`date +"%m%d%Y" -d $initial_date +"%s"`
date: extra operand `+%s'
Try `date --help' for more information.

Thank you

Your date is in mmddyyyy , it needs to be in yyymmdd for date to interpret. Also you don't provide input date format to date command. Format is for display purpose only.

Use it this way:

initial_date=02012014
dt="${initial_date:4}${initial_date:0:4}"
date +"%s" -d "$dt"
1391230800

the problem is, you have to convert your initial_date into a format that date recognize.

02012014 is not one of them, unfortunately.

kent$  date -d "02012014"
date: invalid date ‘02012014’

if you prefer an one-liner, you could try:

date -d $(sed -r 's#(..)(..)(....)#\1/\2/\3#' <<<$initial_date) +%s
1391209200

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM