linux bash - Parse date in custom format

后端 未结 4 896
挽巷
挽巷 2020-12-07 01:19

I have a date in a the %c format (could be any other) and I need to use it in the date command. %c is NOT the American format. It is the G

相关标签:
4条回答
  • 2020-12-07 01:46

    Why don't you store the time as unixtime (ie milliseconds since 1st of january 1970) Like 1388198714?

    The requested exercise in trying to parse all date formats from all around the world as a one shot bash script without reasonable dependecies is slightly ridiculous.

    0 讨论(0)
  • 2020-12-07 01:53

    If you meant the formatting is wrong, I think what you want is:

    NOW=$(date +%c)
    date --date="$NOW" +%d/%m/%Y
    

    note the lowercase %d and %m.

    Locally, this is what I get:

    root@server2:~# NOW=$(date +%c)
    root@server2:~# date --date="$NOW" +%d/%m/%Y
    19/12/2013
    
    0 讨论(0)
  • 2020-12-07 01:59

    You may use libdatetime-format-flexible-perl.

    #!/usr/bin/perl
    use DateTime::Format::Flexible;
    my $date_str = "So 22 Dez 2013 07:29:35 CET";
    $parser = DateTime::Format::Flexible->new;
    my $date = $parser->parse_datetime($date_str);
    print $date
    

    Default output will be 2013-12-22T07:29:35, but since $date is not a regular string but object, you can do something like this:

    printf '%02d.%02d.%d', $date->day, $date->month, $date->year;
    

    Also date behavior probably should be considered as a bug. I think so, because date in the same format but in russian is parsed correctly.

    $ export LC_TIME=ru_RU.UTF-8
    $ NOW="$(date "+%c")"
    $ date --date="$NOW" '+%d.%m.%Y'
    22.12.2013
    

    0 讨论(0)
  • 2020-12-07 02:06

    Not possible with --date as of GNU coreutils 8.22. From the date manual:

    ‘-d datestr’

    ‘--date=datestr’

    Display the date and time specified in datestr instead of the current date and time. datestr can be in almost any common format. It can contain month names, time zones, ‘am’ and ‘pm’, ‘yesterday’, etc. For example, --date="2004-02-27 14:19:13.489392193 +0530" specifies the instant of time that is 489,392,193 nanoseconds after February 27, 2004 at 2:19:13 PM in a time zone that is 5 hours and 30 minutes east of UTC.

    Note: input currently must be in locale independent format. E.g., the LC_TIME=C below is needed to print back the correct date in many locales:

    date -d "$(LC_TIME=C date)"
    

    http://www.gnu.org/software/coreutils/manual/html_node/Options-for-date.html#Options-for-date

    Note it says that the input format cannot be in a locale-specific format.

    There may be other libraries or programs that would recognize more date formats, but for a given date format it would not be difficult to write a short program to convert it to something date recognizes (for example, with Perl or awk).

    0 讨论(0)
提交回复
热议问题