Mohit Rane
Mohit Rane

Reputation: 279

Convert date string into epoch time

I have a string '2015_11_01_00_00' I want this convert into epoch time. I have tried the below code, but could not found it worth.

#!/bin/bash

echo "mohit"

date_var="2015_11_01_00_00"

echo $date_var

arr=$(echo $date_var | tr "_" "\n")

IFS='_ ' read -r -a arr <<< "$date_var"
#echo $arr
echo ${arr[0]}
echo ${arr[1]}
echo ${arr[2]}
echo ${arr[3]}
echo ${arr[4]}

updated_date="${arr[0]}"-"${arr[1]}"-"${arr[2]}"-"${arr[3]}"-"${arr[4]}"
echo $updated_date

TMRW_DATE=`date --date="$updated_date" +"%s"`
echo "$TMRW_DATE"

Upvotes: 0

Views: 77

Answers (3)

Tanjin Alam
Tanjin Alam

Reputation: 2476

i was trying to do the same for postgres sql by following which produce error

SELECT *, DATEDIFF(ss, '1970-01-01T00:00:00.000', punch_time) as EpochSeconds
FROM attendance

but following code did work for me

SELECT EXTRACT(EPOCH FROM punch_time) as EpochTime
FROM attendance;

Upvotes: 0

jlliagre
jlliagre

Reputation: 30823

Here is one way to do it, using GNU date syntax:

#!/bin/bash
echo "mohit"
date_var="2015_11_01_00_00"

TMRW_DATE=$(
    set -- $(echo $date_var | tr "_" " ")
    date --date="$1-$2-$3 $4:$5" +"%s"
)

echo "$TMRW_DATE"

and this should work with OS X date implementation :

#!/bin/bash
echo "mohit"

date_var="2015_11_01_00_00"
TMRW_DATE=$(date -j -f "%Y_%m_%d_%H_%M" "$date_var" +%s)

echo "$TMRW_DATE"

Upvotes: 2

Robin Hsu
Robin Hsu

Reputation: 4484

This one should do the trick:

#!/bin/bash

echo "mohit"

date_var="2015_11_01_00_00"

updated_date=`echo ${date_var} | sed -e 's,_,/,;s,_,/,;s,_, ,;s/_/:/'`
echo ${updated_date}

TMRW_DATE=`date -d "$updated_date" +"%s"`
echo "$TMRW_DATE"

Upvotes: 2

Related Questions