Home > front end >  How to create unique code based on current date in php
How to create unique code based on current date in php

Time:02-23

I have a question, how to create/generate unique code based on current date or input date? For instance, input date = 02-02-2022, the code supposed to look like 20220202-000001.

CodePudding user response:

You can create a Date object using the inegratedDateTime API. Here you can find a list of available formatting options

CodePudding user response:

THIS solution only shows one way to solve the OP's specific problem:

"I have a question, how to create/generate unique code based on current date or input date? For instance, input date = 02-02-2022, the code supposed to look like 20220202-000001.".

THIS solution does not attempt to create a UID across any/and all problem domains.

You could use str_replace() on the date to get rid of the dashes. Then use str_pad() on the count to fill it with 0's and have it "right justify" the actual count.

<?php

function makeCode($date, $count) {

    $dateCode = str_replace("-", "", $date);
    $countCode = str_pad(strval($count), 8, "0", STR_PAD_LEFT);
    
    return $dateCode . "-" . $countCode;
    
}

// test

echo makeCode("02-02-2022", 1); // 02022022-00000001

?>

The 2nd parameter to str_pad() controls the width of the counter, how many zeroes will fill minus the string length the count intself.

  •  Tags:  
  • php
  • Related