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

1

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

3 Comments

+1 because sed will more likely being used in a shell script than PHP ;)
When I run the first piece (sed) I get 1409086714 - is this the timestamp?
@Lenny yes. UNIX timestamp is seconds since 1970-01-01 00:00:00 UTC.
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.