Unix <-> DOS time

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Unix <-> DOS time

Post by redmonkey »

The only need I have had for these functions so far is when writting zipping and unzipping classes.

The zip file format stores the date and time of file modification in the DOS format. If you intend to work with zip files these functions may save you a few hours head scratching.

Code: Select all

<?php
/**
* @return integer             DOS date and time
* @param  integer _timestamp  Unix timestamp
* @desc                       returns DOS date and time of the timestamp or
*                             current local time if no timestamp is given
*/
function unix2dostime($_timestamp = 0)
{
  $timebit = ($_timestamp == 0) ? getdate() : getdate($_timestamp);

  if ($timebit['year'] < 1980)
  {
    return (1 << 21 | 1 << 16);
  }

  $timebit['year'] -= 1980;

  return ($timebit['year']    << 25 | $timebit['mon']     << 21 |
          $timebit['mday']    << 16 | $timebit['hours']   << 11 |
          $timebit['minutes'] << 5  | $timebit['seconds'] >> 1);
}
?>

Code: Select all

<?php
/**
* @return int           Unix timestamp
* @param  int _dostime  DOS date and time
* @desc                 converts a DOS date and time integer to a Unix
*                       timestamp
*/
function dos2unixtime($_dostime)
{
  $sec  = 2 * ($_dostime & 0x1f);
  $min  = ($_dostime >> 5) & 0x3f;
  $hrs  = ($_dostime >> 11) & 0x1f;
  $day  = ($_dostime >> 16) & 0x1f;
  $mon  = (($_dostime >> 21) & 0x0f);
  $year = (($_dostime >> 25) & 0x7f) + 1980;

  return mktime($hrs, $min, $sec, $mon, $day, $year);
}
?>
Post Reply