Linux – How to convert a date with a named month to a unix timestamp with only Busybox tools

busyboxdatelinux

I'm working in an environment where I pretty much only have access to busybox tools, and trying to convert a date in the format Mon Jan 1 23:59:59 2018 GMT to a unix timestamp, in a shell script. I can't change the format of the input time I am parsing. It seems that busybox date can not understand this date format, or any other format with a named month. I have a really ugly script that can do it, but does anyone know of anything nicer?

Edit: the date -D option doesn't work for me, I get

date: invalid option -- 'D'     
BusyBox v1.24.1 (2018-01-11 16:07:45 PST) multi-call binary.     

Usage: date [OPTIONS] [+FMT] [TIME]`

Best Answer

The busybox date2 is fully capable of parsing the date in the given string with some help1 (except for the GMT time zone).

$ gdate='Mon Jan 1 23:59:59 2018 GMT'
$ TZ=GMT0 busybox date -d "$gdate" -D '%a %b %d %T %Y %Z'
Mon Jan  1 23:59:59 GMT 2018

The help is given with the -D option: a description of the source format.

To get a UNIX timestamp, just add the output format expected +'%s':

$  TZ=GMT0 busybox date -d "$gdate" -D '%a %b %d %T %Y %Z' +'%s'
1514851199

1
The busybox date has most of the GNU date command's capabilities and one that the GNU date command doesn't: the -D option. Get the busybox help as follows:

$ busybox date --help

BusyBox v1.27.2 (Debian 1:1.27.2-2) multi-call binary.

Usage: date [OPTIONS] [+FMT] [TIME]

Display time (using +FMT), or set time

    [-s,--set] TIME Set time to TIME
    -u,--utc        Work in UTC (don't convert to local time)
    -R,--rfc-2822   Output RFC-2822 compliant date string
    -I[SPEC]        Output ISO-8601 compliant date string
                    SPEC='date' (default) for date only,
                    'hours', 'minutes', or 'seconds' for date and
                    time to the indicated precision
    -r,--reference FILE     Display last modification time of FILE
    -d,--date TIME  Display TIME, not 'now'
    -D FMT          Use FMT for -d TIME conversion

Note the -D FMT option.


2
Note that you may be able to call busybox date in two ways:

$ busybox date

Or, if a link to busybox with the name date has been installed in the correct PATH directory:

$ date

To verify, just ask for --version or --help to find out which date you have installed.

With GNU date:

$ date --version
date (GNU coreutils) 8.28

Or (busybox date):

$ date --help
BusyBox v1.27.2 (Debian 1:1.27.2-2) multi-call binary.
…
…
Related Question