2

I wrote a shell script that manipulates dates; it gets one or more date strings from the arguments and then outputs a result. Say,

$ datecalc 06/27/2021 01/01/2000
05/10/2005

This script uses the date(1) command for transforming given dates into epoch times, no problem with that. The problem is that it outputs the result in a static format (right now %D). So my main question is: is there a way to get how a date string is formatted?

For instance, I'm looking for a script/function/pipeline/whatever that does the following:

$ getformat "06/27/2021"
%m/%d/%Y
$ getformat "21/06/27"
%y/%m/%d
$ getformat "June 27"
%B %d

Such that I could do something like the following for the script output:

date -d "$result" +$(getformat "$1")

I already checked dateutils to see if any of its programs could do the job, it doesn't seem like so. I wouldn't mind using one or more of dateutils' programs for achieving this, though.

4
  • 5
    What is the expected output of getformat "01/01/01"? Jun 27 at 18:47
  • date uses strftime for output.
    – Jasen
    Jun 27 at 20:47
  • 1
    No. The only real solution is to stop using ambiguous date formats. Use ISO 8601, i.e., YYYY-MM-DD, for all dates. If you use software that generates ambiguous date formats then either fix it or replace it. Clean up dates in existing data files by first figuring out what format the dates were originally written (for numeric-only dates, this requires contextual information, such as the author's locale or cultural background, that is not present in the date itself) in and convert them to ISO 8601.
    – cas
    Jun 28 at 2:35
  • 01/01/01 is easy to parse because the result is the same no matter what format is being used. 01/02/03 would make a better example. I run into annoyances like this all the time, with dates like 06/07/21. The year is easy to figure out, but to identify the date and month you need to know whether the author was American or not. Often the only way is to examine other dates in the same source and try to find at least one example where one of the ambiguous numbers is > 12.
    – cas
    Jun 28 at 2:48
4

Answer: no, there is not

Because as @Kamil hints at, given an ambiguous date of 01/01/01, there is no way to determine whether this is dd/mm/yy, mm/dd/yy, or yy/mm/dd, etc.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.