4

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

Lenny
  • 887
  • 1
  • 11
  • 32
  • possible duplicate of [Convert date time string to UNIX timestamp in bash command](http://stackoverflow.com/questions/10990949/convert-date-time-string-to-unix-timestamp-in-bash-command) – Ciro Santilli OurBigBook.com Jul 25 '15 at 08:59

2 Answers2

5

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
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

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
hek2mgl
  • 152,036
  • 28
  • 249
  • 266