phporacle-databasephp-carbonjdedwards

PHP Julian Date for JDE Oracle


i'm trying to convert a date like 2022-08-09 to a julian date for send it to JDE. The problem is that default php functions like juliantojd() return a different result. The result i expected was something like this

https://nimishprabhu.com/tools/jde-julian-date-converter-online.html

I got this function from a very old code that is doing the job in .asp

function data_giuliana(d){
var pad = "000";

var anno = String(d.getFullYear()).substr(2,2);

var timestmp     = new Date().setFullYear(d.getFullYear(),0,1);
var yearFirstDay = Math.floor(timestmp / 86400000);
var today        = Math.ceil((d.getTime()) / 86400000);
var giorno       = String(today - yearFirstDay);

giorno = pad.substring(0, pad.length - giorno.length) + giorno;

data_giuliana = "1" + anno + giorno;

return data_giuliana;}

I'm trying to convert this function in PHP for use it in my laravel application:

        function data_giuliana($test)
    {
        $pad = "000";
    
        $anno = Carbon::now()->format('Y-m-d');
    
        $timestammp     = Carbon::now()->timestamp;
        $yearFirstDay = floor($timestammp / 86400000);
        $today        = ceil(Carbon::now()->toDateTimeString() / 86400000);
        $giorno       = ($today - $yearFirstDay);
    
      $giorno = substr($pad, strlen($pad) - strlen($giorno)) . $giorno;
    
      $data_giuliana = "1" . $anno . $giorno;
    
      return $data_giuliana;
      dd($data_giuliana);
    }

But it's not working.

Does somebody know any function for php? Or at least help me to convert properly the up function? Thanks a lot


Solution

  • There's a few things that you have to tweak for javascript vs PHP. For instance, javascript uses milliseconds while PHP does not. So you need to divide by 86400, not 86400000, and this also makes the padding unnecessary. You're also trying to append and divide using string dates instead of timestamps, which throws it off. So changing the divisors, fixing the timestamps, and also changing $anno so it only gets the last 2 digits of the year fixes the code like this:

    function data_giuliana($date = null)
    {
        $cdate = $date ? Carbon::parse($date) : Carbon::now();
        $anno = $cdate->format('y'); // 2 digit year
    
        $timestamp = $cdate->copy()->firstOfYear()->timestamp;
        $yearFirstDay = floor($timestamp / 86400);
        $today = ceil($cdate->timestamp / 86400);
        $giorno = ($today - $yearFirstDay);
    
        $data_giuliana = "1" . $anno . $giorno;
    
        return $data_giuliana;
    }
    

    After reading up on what a Julian date is, you can do this much easier with Carbon. z gets the day of the year, starting from 0, so you just need to add 1 to it, and start the format with 1.

    echo Carbon::now()->format('1yz')+1; // 122221