DateTime with microseconds

后端 未结 10 2107
长发绾君心
长发绾君心 2020-12-05 10:02

In my code, I\'m using DateTime objects to manipulate dates, then convert them to timestamp in order to save them in some JSON files.

For some reasons,

10条回答
  •  离开以前
    2020-12-05 10:48

    Beautiful date and time, step by step:

    Note that the microtime() tells time AND microtime (numbers after the period)

    echo microtime(true) ."
    "; //1601674357.9448 sleep(0.99); echo microtime(true) ."
    "; //1601674357.9449 sleep(0.99); echo microtime(true) ."
    "; //1601674357.945

    So let's take the numbers after the period:

    echo substr(microtime(true), 11,4) . "
    "; //945

    But if for a moment you only had 1 or 2 digits after the period? We complete with zeros...

    Ok, now we always have 4 digits which are the microseconds

    echo str_pad(substr(microtime(true), 11,4), 4, '0', STR_PAD_RIGHT) . "
    "; //9450

    So, let's add the date... Final result:

    $date = gmdate('Y-m-d h:i:s.');
    $time = str_pad(substr(microtime(true), 11,4), 4, '0', STR_PAD_RIGHT);
    
    echo $date . $time; //2020-10-02 09:43:57.9450
    

提交回复
热议问题