Bash convert date to timestamp

I have a date in format 'YYYYMMDDHHMMSS', and I need to convert it to a Unix timestamp.

I tried date -d '20140826225834', but I got an error 'invalid date'. I assume that I have to convert what I have ( 20140826225834) to an accepted date and then convert it to a timestamp? Edit: I set this date from 2014-08-21_23.03.07- perhaps it would be easier to convert this date type

+4
source share
2 answers

You should probably change the format of the date you receive so that you datecan process it. I am changing it in format YYYY/MM/DD HH:MM:SSwith sed.

$ date -d"$(sed -r 's#(.{4})(.{2})(.{2})(.{2})(.{2})#\1/\2/\3 \4:\5:#' <<< "20140826225834")" "+%s"
1409086714

In parts:

$ sed -r 's#(.{4})(.{2})(.{2})(.{2})(.{2})#\1/\2/\3 \4:\5:#' <<< "20140826225834"
2014/08/26 22:58:34

$ date -d"2014/08/26 22:58:34"
Tue Aug 26 22:58:34 CEST 2014

$ date -d"2014/08/26 22:58:34" "+%s"
1409086714
+5
source

PHP, PHP strtotime() :

#!/bin/bash

input="20140826225834"
output=$(php -r 'echo strtotime("'"$input"'");')

echo "$output" # 1409086714
0

All Articles