Micheal Perr
Micheal Perr

Reputation: 1895

Convert a date in Shell

This is a hart one, how do I convert a date like

12-23-11 13:37

In something like(seconds should always be 00)

Fri Dec 23 13:18:58 CET 2011

?

Upvotes: 0

Views: 292

Answers (2)

William Pursell
William Pursell

Reputation: 212248

With gnu date 5.97, you can do:

$ date -d '11-12-23 13:37'

to get what you want, so all you need to do is massage your input.

Since gnu date is not ubiquitous, here's a quick perl script that does what you want:

$ echo 12-23-11 13:37 |
    perl -MTime::Local -wnE '
    y/-:/  /;
    @F=split;
    say scalar localtime timelocal( 0, $F[4], $F[3], $F[1], $F[0] - 1,$F[2]);
'
Fri Dec 23 13:37:00 2011

(Requires perl 5.10 for -E and say, but should work in older perl using -e and print.)

Upvotes: 2

Trott
Trott

Reputation: 70075

If this is a script for yourself and not something that will have to run in a million different environments, then depending on what version of date you have available, you should be able to use it.

Read the man page for your particular version of date. For example, if it's the version documented at http://ss64.com/bash/date.html, you can use --date for the input string, etc.

On Mac OS X, use the -f option to specify the input format, the -j option so that it doesn't try to set the date, and with specifying the output format on the command line.

Upvotes: 1

Related Questions