Forum Discussion

srk_powerbi's avatar
srk_powerbi
Helper II
5 years ago
Solved

function to convert date to integer

hi,  i need to create a function in power query which takes any date as input and converts that to int.  For example 01/01/2001 (mm/dd/yyyy) equals to 1 as integer. . Taking this as reference  i nee...
  • v-angzheng-msft's avatar
    5 years ago

     Hi, srk_powerbi 

     

    Please try the following steps:

    1. Create a new table by copying the date column
    2. Use the standard ribbon earlier function to get the minimum date
    3. Merge the two tables according to the date column and fill the minimum date down
    4. Subtract the minimum date from the date to get a new column
    5. Get the number of days with Duration fuction, and then add one to the number of days

     

    Step 4 and step 5 I combined it into the following formula

    = Table.AddColumn(#"Filled Down", "New column", each Duration.Days([Date]-[Min.Column1])+1)

    I created a simple sample to illustrate this.

    Sample:

    Result:

    Code:

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("VdCxDYNAAEPRXagj3dmGJDcLYv81EA3yL3/lJ5/n5qHhaW3X5wl3pGPvODq+Hb+Of8fq0ETBICAEhcAQHAJEkAgUwWJYzD9gMSyGxbAYFsPisqTvT9+fvj99f/r+9P3p+zOwszA6UTAICEEhMN77rxs=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Date = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Date", type date}}),
        #"Merged Queries" = Table.NestedJoin(#"Changed Type", {"Date"}, Min, {"Column1"}, "Min", JoinKind.LeftOuter),
        #"Expanded Min" = Table.ExpandTableColumn(#"Merged Queries", "Min", {"Column1"}, {"Min.Column1"}),
        #"Changed Type1" = Table.TransformColumnTypes(#"Expanded Min",{{"Min.Column1", type date}}),
        #"Filled Down" = Table.FillDown(#"Changed Type1",{"Min.Column1"}),
        #"Added Custom" = Table.AddColumn(#"Filled Down", "New column", each Duration.Days([Date]-[Min.Column1])+1),
        #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Min.Column1"})
    in
        #"Removed Columns"

    Please refer to the attachment below for details

     

     

    Is this the result you want? Hope this is useful to you

    Please feel free to let me know If you have further questions

     

    Best Regards,
    Community Support Team _ Zeon Zheng
    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.