title: linux bash - Parse date in custom format
body: <p>I have a date in a the <code>%c</code> format <em>(could be any other)</em> and I need to use it in the date command. <code>%c</code> is NOT the American format. It is the German one because it's a German server. This also did not work properly on an American server. (Locales set to German or American)</p>
  
  <p>This does not work (error included):</p>
  
  <pre><code>user@server:~$ NOW=$(date +%c); echo $NOW
  Do 19 Dez 2013 22:33:28 CET
  user@server:~$ date --date="$NOW" +%d/%m/%Y
  date: ungültiges Datum „Do 19 Dez 2013 22:33:28 CET“
  </code></pre>
  
  <p><em>(date: ungültiges Datum „Do 19 Dez 2013 22:33:28 CET“ = <code>date: invalid date „Do 19 Dez 2013 22:33:28 CET“</code>)</em></p>
  
  <p>The difficulty is that I don't know which locale or even whci dateformat will be used later since the user can set their own format. So a simple specific parsing solution ist not really going to work!</p>
  
  <p>But how do I do it?</p>
  
  <p>To gerneralize the issue:</p>
  
  <p>If I have a date format <code>format1</code> <em>(which could be any or at least one that can be reversed)</em> I can use date to get a formatted date. But if I want to format it to another date (<code>format2</code>) how do I do it?<br>
  Any solution using anything else than the coreutils is pointless since I am trying to develop a bash script for as many unix machines as possible.</p>
  
  <pre><code>DATE=$(date "+$format1")
  
  date --date="$DATE" "+$format2" # Error in most cases!
  </code></pre>
  
  <p>This is needed because I have a command which the user can give a date format. This date string is going to be displayed. But in a later step I need to convert this date string into another fixed one. I can manipulate the whcih format the command will get and I can maniplulate the output <em>(or what the user will see)</em>.<br>
  I cannot run the command twice because it is very time consuming.</p>
  
  <hr>
  
  <h2>Update:</h2>
  
  <p>I have found something like a solution:</p>
  
  <pre><code># Modify $user_format so it can be parsed later
  user_format="$user_format %s"
  
  # Time consuming command which will print a date in the given format
  output=$(time_consuming_command params "$user_format" more params)
  
  # This will only display what $user_format used to be
  echo ${output% *}
  
  # A simple unix timestamp parsing ("${output##* }" will only return the timestamp)
  new_formated_date=$(date -d "1970-01-01 ${output##* } sec UTC" "+$new_format")
  </code></pre>
  
  <p>This is working and might be helpful to others. So I will share this with you.</p>