1

Possible Duplicate:
Convert date formats in bash

I need to convert a date such as

2012-06-01T19:05:00+02:00

to something like this

01-06-2012 19:05

Ideally using sed or awk. How do I do this?

Community
  • 1
  • 1
fabsh
  • 75
  • 6
  • I'm sorry but that doesn't tell me how to do it. I did find that post before but I'm to stupid to make it work. – fabsh Jun 02 '12 at 14:09
  • Please improve questions like this by showing why whatever you tried isn't working. Otherwise, `man 1 date` is your friend. – Todd A. Jacobs Jun 02 '12 at 14:25

3 Answers3

5

This can be done without resorting to sed or awk, since bash itself can do most of the required string replacements. Specifically, you just need to:

  1. replace T with a space, and
  2. remove your timezone information.

The rest of the date formatting can be handled by the date command.

$ date_string='2012-06-01T19:05:00+02:00'
$ date_string="${date_string/T/ }"
$ date_string="${date_string/+*/}"
$ date -d "$date_string" '+%d-%m-%Y %H:%M'
01-06-2012 19:05
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • The square brackets aren't necessary around the "T". The quotes can be omitted around the parameter expansions. – Dennis Williamson Jun 02 '12 at 14:36
  • @DennisWilliamson You're right. I'd originally had a more complicated expression which included a character class. I've gone ahead and removed the character class, as well as an extraneous space in one of the original replacement expressions, to make the intent more clear. – Todd A. Jacobs Jun 02 '12 at 14:38
4
echo "2012-06-01T19:05:00+02:00"|sed 's/\(.*\)T\([0-9]*:[0-9]*\).*/\1 \2/'
2012-06-01 19:05

To explain what it does:

  • match everything up to the T and refer to it as \1 later
  • match any following digits, followed by a ":", followed by any following digits and refer to that group as \2
  • print first match, space, second match
naumcho
  • 18,671
  • 14
  • 48
  • 59
2
date -d "$(echo '2012-06-01T19:05:00+02:00' | sed 's/T/ /; s/+.*//')" '+%d-%m-%Y %H:%M'
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439