Search code examples
bashmacosbsd

Getting Epochal Time from Date String


I have a process that outputs a date like this (note the padding in front of the day (4):

Mon Jun  4 17:53:42 2018

I want to get the epochal time, so I've tried:

echo "Mon Jun  4 17:53:42 2018" | xargs -0 date -j -f "%a %b %d %T %Y" +%s

This does work, but I am left with the annoying:

Warning: Ignoring 1 extraneous characters in date string (
)

I can live with the warning, but I've tried removing the double spacing with sed:

echo "Mon Jun  4 17:53:42 2018" | sed -E 's/\ +/\ /g'

which returns:

Mon Jun 4 17:53:42 2018

But when I try to pipe this to the date format, I get the warning again (as though sed is not doing its thing).


Solution

  • The problem was not whitespace, but a newline. I removed sed and replaced with tr -d "\n" to remove the offending character:

    echo "Mon Jun 4 17:53:42 2018" | tr -d "\n" | xargs -0 date -j -f "%a %b %d %T %Y" +%s