Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
2 years ago
Solved

Free text date column correction

Hi All, I have a report that has a free text arrival date column that has a lot of inconsistent date formats. I'm looking to change the all to dd/mm/yyyy, some of them don’t have the year included b...
  • ronrsnfld's avatar
    2 years ago

    Here's one method.

    The transforms I did should be clear in the code.

    I assumed that there would never be an entry with just Month and Year

    I also assumed that if a date was ambiguous, it would be interpreted as "DMY".

    The routine converts all of your dates to real dates. How they are displayed will depend on your Windows Regional Settings in Power Query, and on how you set the date formatting in Power BI (or Excel).

     

    If you need them displayed as DMY in Power Query, you may need to convert them to text strings as otherwise the display in PQ will be dependent on the windows regional settings of the computer. But then they won't be "real dates".

     

    let
        Source = Excel.CurrentWorkbook(){[Name="Dates"]}[Content],
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Estimated Arrival Date", type text}}),
        #"Normalize Dates" = Table.AddColumn(#"Changed Type", "Normalized Dates", (c)=> 
            let 
                split = Text.SplitAny(c[Estimated Arrival Date],"./-"),
                addYear = if List.Count(split) = 2 then split & {DateTime.ToText(DateTime.FixedLocalNow(),"yyyy")} else split,
                trim = List.Transform(addYear, each Text.Trim(_)),
                #"3 Max" = List.Transform(trim, each 
                    if List.ContainsAll({"A".."Z"},Text.ToList(_),Comparer.OrdinalIgnoreCase)
                    then Text.Start(_,3) else _),
                dt = try Date.From(Text.Combine( #"3 Max","-"),"en-150") otherwise Date.From(Text.Combine( #"3 Max","-"),"en-US")
    
            in dt, type date),
        #"Removed Columns" = Table.RemoveColumns(#"Normalize Dates",{"Estimated Arrival Date"})
    in
        #"Removed Columns"

    It converts all the dates in your example: