Lenny
Lenny

Reputation: 917

Bash convert date to timestamp

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

I tried to date -d '20140826225834' but I get 'invalid date' error. I asume that I would have to convert what I have ( 20140826225834 ) to accepted date and then convert it to timestamp? Edit: I have sed this date from 2014-08-21_23.03.07 - maybe it would be easier to convert this date type

Upvotes: 4

Views: 9108

Answers (2)

hek2mgl
hek2mgl

Reputation: 157967

You could use PHP, since PHP's strtotime() can parse your input format:

#!/bin/bash

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

echo "$output" # 1409086714

Upvotes: 1

fedorqui
fedorqui

Reputation: 289565

You should probably change the format of the date you get, so that date can handle it. I change it to a YYYY/MM/DD HH:MM:SS format with sed.

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

By pieces:

$ 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

Upvotes: 5

Related Questions