简体   繁体   中英

Change datetime to timestamp in bash script

I have a json in file myTime { "beginTime": "2014-Mar-19 02:15:00", "endTime": "2014-Mar-29 02:00:00" }

I want to get beginTime and change it to timestamp.

I get beginTime by the following code:

beginTime=($(jq -r '.beginTime' myTime))

I replace Mar by 03 :

beginTime=($(echo "$beginTime" | sed -r 's/[Mar]+/03/g'))

I change it to time stamp :

date -d "$beginTime" "+%s"

I got 1395162000 , it mean only change 2014-03-19 because $beginTime give 2014-03-19 , first element of array. so I tried another code

date -d "${beginTime[@]}" "+%s"

now I got

date: extra operand `+%s'

but this code is ok

date -d "2014-03-19 02:15:00" "+%s"

Could anyone help me?

Do not use array variables - you need to capture date and time as a single string:

beginTime=$(jq -r '.beginTime' myTime | sed 's/Mar/03/') # "2014-03-19 02:15:00"

Note that I've combined your first two commands into one.

(As an aside: regex /[Mar]+/ happens to work in this case, but is not what you intended - use /Mar/ instead. /[Mar]+/ matches any span of at least length 1 composed of any of the following characters in any sequence: M , a , r .)

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