1

How can I get the epoch if I have a string in the following format?
1/30/2017 11:14:55 AM
The following does not work:

$ date -j  '1/30/2017 11:14:55 AM' +'%m/%d/%Y %H:%M:%S'  
date: illegal time format
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Jim
  • 9,750
  • 15
  • 57
  • 84

1 Answers1

4

Just specify the input format with -f:

$ date -jf '%m/%d/%Y %H:%M:%S %p' '1/30/2017 11:14:55 AM' '+%m/%d/%Y %H:%M:%S'
01/30/2017 11:14:55

What goes after + is the output format. If you want the epoch time, that would be +%s.

(note that there's nothing bash-specific in that code. That code would be parsed the same in any shell, even non-Bourne-like ones. date is not a bash builtin command, here it's the date command found on the file system, specifically one that supports those -f/-j BSD extensions. On non-BSD systems that command is likely not to work regardless of whether the shell is bash or other. Some shells like zsh or ksh93 have time-parsing capabilities built in but not bash)

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • What I want is to parse that string and get the epoch i.e. a numeric value. I thought I could do that with `date`. Your answer just prints the string back. Unless I misunderstood what I need to do – Jim Jan 31 '17 at 22:27
  • 1
    @Jim Change the last argument to `'+%s'` and you'll get number of seconds since the Epoch UTC. – Kusalananda Jan 31 '17 at 22:35