Php date to integer

date

Returns a string formatted according to the given format string using the given integer timestamp (Unix timestamp) or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time() .

Unix timestamps do not handle timezones. Use the DateTimeImmutable class, and its DateTimeInterface::format() formatting method to format date/time information with a timezone attached.

Parameters

Note: date() will always generate 000000 as microseconds since it takes an int parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.

The optional timestamp parameter is an int Unix timestamp that defaults to the current local time if timestamp is omitted or null . In other words, it defaults to the value of time() .

Return Values

Returns a formatted date string.

Errors/Exceptions

Every call to a date/time function will generate a E_WARNING if the time zone is not valid. See also date_default_timezone_set()

Changelog

Version Description
8.0.0 timestamp is nullable now.

Examples

Example #1 date() examples

// set the default timezone to use.
date_default_timezone_set ( ‘UTC’ );

// Prints something like: Monday
echo date ( «l» );

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );

// Prints: July 1, 2000 is on a Saturday
echo «July 1, 2000 is on a » . date ( «l» , mktime ( 0 , 0 , 0 , 7 , 1 , 2000 ));

/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date ( DATE_RFC2822 );

// prints something like: 2000-07-01T00:00:00+00:00
echo date ( DATE_ATOM , mktime ( 0 , 0 , 0 , 7 , 1 , 2000 ));
?>

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

$tomorrow = mktime ( 0 , 0 , 0 , date ( «m» ) , date ( «d» )+ 1 , date ( «Y» ));
$lastmonth = mktime ( 0 , 0 , 0 , date ( «m» )- 1 , date ( «d» ), date ( «Y» ));
$nextyear = mktime ( 0 , 0 , 0 , date ( «m» ), date ( «d» ), date ( «Y» )+ 1 );
?>

Note:

This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm
$today = date ( «m.d.y» ); // 03.10.01
$today = date ( «j, n, Y» ); // 10, 3, 2001
$today = date ( «Ymd» ); // 20010310
$today = date ( ‘h-i-s, j-m-y, it is w Day’ ); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date ( ‘\i\t \i\s \t\h\e jS \d\a\y.’ ); // it is the 10th day.
$today = date ( «D M j G:i:s T Y» ); // Sat Mar 10 17:16:18 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:18 m is month
$today = date ( «H:i:s» ); // 17:16:18
$today = date ( «Y-m-d H:i:s» ); // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>

To format dates in other languages, IntlDateFormatter::format() can be used instead of date() .

Notes

Note:

To generate a timestamp from a string representation of the date, you may be able to use strtotime() . Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL’s » UNIX_TIMESTAMP function).

Timestamp of the start of the request is available in $_SERVER[‘REQUEST_TIME’] .

See Also

  • DateTimeImmutable::__construct() — Returns new DateTimeImmutable object
  • DateTimeInterface::format() — Returns date formatted according to given format
  • gmdate() — Format a GMT/UTC date/time
  • idate() — Format a local time/date part as integer
  • getdate() — Get date/time information
  • getlastmod() — Gets time of last page modification
  • mktime() — Get Unix timestamp for a date
  • IntlDateFormatter::format() — Format the date/time value as a string
  • time() — Return current Unix timestamp
  • Predefined DateTime Constants

User Contributed Notes

  • Date/Time Functions
    • checkdate
    • date_​add
    • date_​create_​from_​format
    • date_​create_​immutable_​from_​format
    • date_​create_​immutable
    • date_​create
    • date_​date_​set
    • date_​default_​timezone_​get
    • date_​default_​timezone_​set
    • date_​diff
    • date_​format
    • date_​get_​last_​errors
    • date_​interval_​create_​from_​date_​string
    • date_​interval_​format
    • date_​isodate_​set
    • date_​modify
    • date_​offset_​get
    • date_​parse_​from_​format
    • date_​parse
    • date_​sub
    • date_​sun_​info
    • date_​sunrise
    • date_​sunset
    • date_​time_​set
    • date_​timestamp_​get
    • date_​timestamp_​set
    • date_​timezone_​get
    • date_​timezone_​set
    • date
    • getdate
    • gettimeofday
    • gmdate
    • gmmktime
    • gmstrftime
    • idate
    • localtime
    • microtime
    • mktime
    • strftime
    • strptime
    • strtotime
    • time
    • timezone_​abbreviations_​list
    • timezone_​identifiers_​list
    • timezone_​location_​get
    • timezone_​name_​from_​abbr
    • timezone_​name_​get
    • timezone_​offset_​get
    • timezone_​open
    • timezone_​transitions_​get
    • timezone_​version_​get

    Источник

    idate

    Преобразует текущую дату и время в целое число в соответствии со строкой форматирования format . Если аргумент timestamp задан, расчет будет произведен для этой временной метки, если нет — будет использовано локальное время. Другими словами, timestamp — необязательный аргумент и по умолчанию равен значению time() .

    В отличие от функции date() , idate() принимает только один символ в аргументе format .

    Список параметров

    Допустимые символы в строке аргумента format

    format символ Описание
    B Эталонное время/Время Интернета
    d День месяца
    h Час (12 часовой формат)
    H Час (24 часовой формат)
    i Минуты
    I (i в верхнем регистре) возвращает 1 если активировано DST, или 0 в противном случае
    L (l в верхнем регистре) возвращает 1 для високосного года, 0 в противном случае
    m Номер месяца
    s Секунды
    t Количество дней в текущем месяце
    U Время в секундах, от начала эпохи UNIX — 1 января 1970 00:00:00 UTC — то же, что time()
    w День недели (0 — Воскресенье)
    W ISO-8601 — Номер недели года, неделя начинается с понедельника
    y Год (1 или 2 цифры — см. примечание ниже)
    Y Год (4 цифры)
    z День года
    Z Временная зона — смещение в секундах

    Необязательный параметр timestamp представляет собой integer метку времени, по умолчанию равную текущему локальному времени, если timestamp не указан. Другими словами, значение по умолчанию равно результату функции time() .

    Возвращаемые значения

    idate() всегда возвращает integer и не может начинаться с нуля, поэтому idate() может вернуть меньше цифр, чем вы ожидаете. См. примеры ниже.

    Ошибки

    Каждый вызов к функциям даты/времени при неправильных настройках временной зоны сгенерирует ошибку уровня E_NOTICE , и/или ошибку уровня E_STRICT или E_WARNING при использовании системных настроек или переменной окружения TZ . Смотрите также date_default_timezone_set()

    Список изменений

    Теперь ошибки, связанные с временными зонами, генерируют ошибки уровня E_STRICT и E_NOTICE .

    Примеры

    Пример #1 Пример использования idate()

    $timestamp = strtotime ( ‘1st January 2004’ ); //1072915200

    // это выведет год в 2-х знаковом представлении
    // поскольку первая цифра «0», будет выведено
    // только «4»
    echo idate ( ‘y’ , $timestamp );
    ?>

    Смотрите также

    • date() — Форматирует вывод системной даты/времени
    • getdate() — Возвращает информацию о дате/времени
    • time() — Возвращает текущую метку времени Unix

    Источник

    idate

    Returns a number formatted according to the given format string using the given integer timestamp or the current local time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time() .

    Unlike the function date() , idate() accepts just one char in the format parameter.

    Parameters

    The following characters are recognized in the format parameter string

    format character Description
    B Swatch Beat/Internet Time
    d Day of the month
    h Hour (12 hour format)
    H Hour (24 hour format)
    i Minutes
    I (uppercase i) returns 1 if DST is activated, 0 otherwise
    L (uppercase l) returns 1 for leap year, 0 otherwise
    m Month number
    N ISO-8601 day of the week ( 1 for Monday through 7 for Sunday)
    o ISO-8601 year (4 digits)
    s Seconds
    t Days in current month
    U Seconds since the Unix Epoch — January 1 1970 00:00:00 UTC — this is the same as time()
    w Day of the week ( 0 on Sunday)
    W ISO-8601 week number of year, weeks starting on Monday
    y Year (1 or 2 digits — check note below)
    Y Year (4 digits)
    z Day of the year
    Z Timezone offset in seconds

    The optional timestamp parameter is an int Unix timestamp that defaults to the current local time if timestamp is omitted or null . In other words, it defaults to the value of time() .

    Return Values

    Returns an int on success, or false on failure.

    As idate() always returns an int and as they can’t start with a «0», idate() may return fewer digits than you would expect. See the example below.

    Errors/Exceptions

    Every call to a date/time function will generate a E_WARNING if the time zone is not valid. See also date_default_timezone_set()

    Changelog

    Version Description
    8.2.0 Adds the N (ISO-8601 day of the week) and o (ISO-8601 year) format characters.
    8.0.0 timestamp is nullable now.

    Examples

    Example #1 idate() example

    $timestamp = strtotime ( ‘1st January 2004’ ); //1072915200

    // this prints the year in a two digit format
    // however, as this would start with a «0», it
    // only prints «4»
    echo idate ( ‘y’ , $timestamp );
    ?>

    See Also

    • DateTimeInterface::format() — Returns date formatted according to given format
    • date() — Format a Unix timestamp
    • getdate() — Get date/time information
    • time() — Return current Unix timestamp

    User Contributed Notes

    • Date/Time Functions
      • checkdate
      • date_​add
      • date_​create_​from_​format
      • date_​create_​immutable_​from_​format
      • date_​create_​immutable
      • date_​create
      • date_​date_​set
      • date_​default_​timezone_​get
      • date_​default_​timezone_​set
      • date_​diff
      • date_​format
      • date_​get_​last_​errors
      • date_​interval_​create_​from_​date_​string
      • date_​interval_​format
      • date_​isodate_​set
      • date_​modify
      • date_​offset_​get
      • date_​parse_​from_​format
      • date_​parse
      • date_​sub
      • date_​sun_​info
      • date_​sunrise
      • date_​sunset
      • date_​time_​set
      • date_​timestamp_​get
      • date_​timestamp_​set
      • date_​timezone_​get
      • date_​timezone_​set
      • date
      • getdate
      • gettimeofday
      • gmdate
      • gmmktime
      • gmstrftime
      • idate
      • localtime
      • microtime
      • mktime
      • strftime
      • strptime
      • strtotime
      • time
      • timezone_​abbreviations_​list
      • timezone_​identifiers_​list
      • timezone_​location_​get
      • timezone_​name_​from_​abbr
      • timezone_​name_​get
      • timezone_​offset_​get
      • timezone_​open
      • timezone_​transitions_​get
      • timezone_​version_​get

      Источник

      ArtVk & Bugtrack

      Данная функция преобразует дату в строку. На выходе получим количество секунд от базовой даты — 01-01-1970 до введенной нами $date,
      в данном примере получим «0» (т. к. $date = ‘1970-01-01 00:00:00’ ).

      Теперь к данному числу можно прибавлять количество секунд в днях, часах и т.д. — получая код даты следующего дня или часа и т.д.

      echo date(«d-m-Y», $int_date + 86400); — //Получим строку следующего дня ‘1970-01-02’

      Для создания списка от одной даты до другой воспользуемся ниже описанной функцией:

      function Get_date_list($date, $date2)
      $file = ‘brute.txt’;

      //Вводим дату начала. для нашего списка.
      echo ‘
      Начнем наш список с даты — ‘.$date.’ по ‘.$date2.’
      ‘;

      $int_date = strtotime(«$date GMT»); //Получаем дату выраженную типом int (кол-во секунд от 1970-01-01)
      $int_date2 = strtotime(«$date2 GMT»); //Получаем дату выраженную типом int (кол-во секунд от 1970-01-01)

      echo ‘Количество секунд1 от базовой даты (01-01-1970) — ‘.$int_date.’ — ‘.gettype($int_date).’
      ‘;
      echo ‘Количество секунд2 от базовой даты (01-01-1970) — ‘.$int_date2.’ — ‘.gettype($int_date2).’
      ‘;

      //Преобразуем число в дату.
      echo date(«d-m-Y», $int_date).’
      ‘;

      //Запись
      $str = date(«dmY», $int_date);
      file_put_contents($file, $str.»\n», FILE_APPEND | LOCK_EX);

      //Для получения следующей даты прибавим +86400 (кол-во секунд в одних сутках)
      $int_date = $int_date + 86400;
      >
      >
      Get_date_list(‘1989-01-01 00:00:00’, ‘2013-01-01 00:00:00’); //От какой даты по какую.
      ?>

      Источник

    Читайте также:  Подключение CSS файла
Оцените статью