create datetime from timestamp php

How to get time and date from datetime stamp in PHP?

How to achieve that? Can you give me example?

7 Answers 7

edit: To keep the AM/PM format use

strtotime creates a UNIX timestamp from the string you pass to it.

For more information about date() function, plz visit http://php.net/manual/en/function.date.php

This is probably not the cleanest way of doing it, but you can use an explode (note that there is NO validation at all here). It will be faster than a proper date manipulation.

If your version of PHP is new enough, check out date_parse() and the array it returns. You can then format date or time portions using the relevant entries.

This should do the trick:

You could also do something like this but it’s not preferred way:

Yes this is possible, and the perfect example can be found here http://php.net/manual/en/function.date.php

Not the answer you’re looking for? Browse other questions tagged php date or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

DateTime::createFromFormat

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Description

Parameters

The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.

The Unix epoch is 1970-01-01 00:00:00 UTC.

String representing the time.

A DateTimeZone object representing the desired time zone.

If timezone is omitted or null and datetime contains no timezone, the current timezone will be used.

The timezone parameter and the current timezone are ignored when the datetime parameter either contains a UNIX timestamp (e.g. 946684800 ) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00 ).

Return Values

Returns a new DateTime instance or false on failure.

Changelog

Version Description
7.3.0 The v format specifier has been added.

Examples

Example #1 DateTime::createFromFormat() example

The above examples will output:

Example #2 Intricacies of DateTime::createFromFormat()

The above example will output something similar to:

Example #3 Format string with literal characters

The above example will output something similar to:

See Also

User Contributed Notes 27 notes

Be warned that DateTime object created without explicitely providing the time portion will have the current time set instead of 00:00:00.

Be aware:
If the day of the month is not provided, creating a DateTime object will produce different results depending on what the current day of the year is.
This is because the current system date will be used where values are not provided.

// on August 1st
printMonth ( «April» );
// outputs April

// on August 31st
printMonth ( «April» );
// outputs May
?>

In this case, each and every character on that string has to be escaped as shown below.

createFromFormat(‘U’) has a strange behaviour: it ignores the datetimezone and the resulting DateTime object will always have GMT+0000 timezone.

?>

The problem is microtime() and time() returning the timestamp in current timezone. Instead of using time you can use ‘now’ but to get a DateTimeObject with microseconds you have to write it this way to be sure to get the correct datetime:

Parsing RFC3339 strings can be very tricky when their are microseconds in the date string.

Since PHP 7 there is the undocumented constant DateTime::RFC3339_EXTENDED (value: Y-m-d\TH:i:s.vP), which can be used to output an RFC3339 string with microseconds:

Note: the difference between «v» and «u» is just 3 digits vs. 6 digits.

echo phpversion ();
// 7.2.7-1+ubuntu16.04.1+deb.sury.org+12019-01-102019-01-01

Reportedly, microtime() may return a timestamp number without a fractional part if the microseconds are exactly zero. I.e., «1463772747» instead of the expected «1463772747.000000». number_format() can create a correct string representation of the microsecond timestamp every time, which can be useful for creating DateTime objects when used with DateTime::createFromFormat():

If you’re here because you’re trying to create a date from a week number, you want to be using setISODate, as I discovered here:

Источник

Как переводить дату в метку времени в php примеры код скрипт

Как из даты вернуть временную метку, как преобразовать дату во временную метку, способы перегнать дату в timestamp!

Все способы вернуть из даты временную метку

Как преобразовать дату в метку времени! Мы будем сегодня пользоваться функцией strtotime.

Как-то затрагивали тему времени в php и сегодня нам потребовалось дату конвертировать обратно в метку времени(timestamp)!

У есть дата такого формата… запените эту дату вместе с часами и минутами.

Как преобразовать дату во временную метку с помощью strtotime

Результат возврата из даты временную метку:

2019-02-05 11:38 И теперь в качестве функции, которая вернет нам метку времени будем использовать mktime, но сперва нам потребуется, для этой функции, проделать пару манипуляций.

Разобьем с помощью explode в массив:

и сталось вернуть временную метку из даты:

Пропускаем через класс DateTime + присваиваем переменной:

format возвращаем строку даты, преобразованной согласно переданному формату и выводим:

Пропускаем через класс DateTime + присваиваем переменной:

getTimestamp получим метку времени в стиле Unix

Функция date_create создает объект ‘дата’, с которым в дальнейшем можно выполнять некоторые операции.

Пропускаем через функцию date_create + присваиваем переменной:

date_format строку, отформатированную в соответствии с указанным шаблоном format.

1549366680 Либо вместо date_format можно использовать date_timestamp_get

Думаю этих способов вернуть временную метку из даты будет достаточно!

Раз уж выше мы сделали перевод времени в метку времени, то и можно сделать наоборот.

В форме ввода введите метку времени «timestamp», чтобы найти по ней дату.

Сообщение системы комментирования :

Форма пока доступна только админу. скоро все заработает. надеюсь.

Источник

DateTime::__construct

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

Описание

Создаёт и возвращает новый экземпляр класса DateTime.

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

Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.

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

Возвращает созданный объект класса DateTime. Процедурный стиль возвращает false в случае возникновения ошибки.

Ошибки

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

Версия Описание
7.1.0 Теперь микросекунды будут заполняться корректным значением, а не ‘00000’.

Примеры

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

Результат выполнения данных примеров:

Пример #2 Хитрости при использовании DateTime::__construct()

Результатом выполнения данного примера будет что-то подобное:

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

User Contributed Notes 18 notes

The theoretical limits of the date range seem to be «-9999-01-01» through «9999-12-31» (PHP 5.2.9 on Windows Vista 64):

Note that the DateTime ctor also accepts boolean false and empty strings, and treats them the same as NULL (i.e. result is current date and time). This may lead to unexpected results if you forward function return values without explicitly checking them first.

Empty arrays and boolean true trigger PHP warnings OTOH.

(checked with PHP 5.5.18)

// New Timezone Object
$timezone = new DateTimeZone ( ‘America/New_York’ );

It is worth noting:

If you have not setup a default timezone, an Exception (or error if PHP

If time cannot be parsed an exception of type Exception is thrown which can be caught, however an E_WARNING is emitted as well. This might be confusing if you are converting warnings to exceptions in your error or shutdown handler.

Be careful working with MySQL dates representing point of transition to Daylight Saving Time.
The constructor of DateTime will convert timezone abbreviation to DST but not the time.

= new DateTimeZone ( ‘Europe/Sofia’ );

$transitionToDst = ‘2014-03-30 03:00:00’ ;

Watch out – this means that these two are NOT equivalent, they result in different timezones (unless your current timezone is GMT):

About constructing a DateTime, instead of just using the year it seems working when date matches the pattern «YYYY-MM»

— Returns the year correctly: «YYYY-MM»

— Ignores the given input and returns the year from NOW: «YYYY»

RESULTS/SCOPE:
— Linux (May 24, 2019)
— PHP 7.2.17 (cli)

Using this in a try catch to verify a string is in a valid date format is unreliable. Single letter strings used for the first argument (time string) of the constructor allows a new instance of the class to be created, without any exception or error.

I’m surprised this hasn’t been mentioned, but when constructing a DateTime with just the year as a string, DateTime will pre-initialize itself with NOW and then replace the year, so if today is 7/12/2016:

print((new DateTime ( ‘2015’ ))-> modify ( ‘+1 day’ )-> format ( ‘Y-m-d’ ));
?>

results in 2016-07-13

This seems to work as expected, at least now:

Also forgot to mention, that MySQL «zeroed» dates do not throw an error but produce a non-sensical date:

?>

Another good reason to write your own class that extends from DateTime.

When passing a non US or SQL date string the date will be formatted incorrectly.

// UK date d/m/Y.
$date_time = «08/03/2016 00:00:00»;

$dt = new DateTime($date_time, new DateTimeZone(«Europe/London»));

Impossible times due to daylight savings are handled by this function in a way similar to impossible dates, with the difference that this is not an error (i.e. a consequent call to DateTime::getLastError() yields nothing).

For example:
In the timezone «Europe/Berlin» on Sunday, March 30 2014 there was no 02:30 am, because that our is being skipped due to daylight savings on that day.

/*
Yields:
array(4) <
‘warning_count’ =>
int(0)
‘warnings’ =>
array(0) <
>
‘error_count’ =>
int(0)
‘errors’ =>
array(0) <
>
>
The impossible time ‘2014-03-30T02:30:00’ is interpreted as: 2014-03-30T03:30:00+0200
*/
?>

That is similar to how, for example, Febuary 29, 2014 would be handled, which would be interpreted as March 1, 2014. The difference is, that with the date that would be an error, with the time it is not.

Ambigous times due to daylight savings are handled as the second possibility. For example the time 2:30 am occurred twice on October 26, 2014 in the timezone «Europe/Berlin».

/*
Yields:
The ambiguous time ‘2014-10-26T02:30:00’ is interpreted as: 2014-10-26T02:30:00+0100
*/
?>

Note that «2014-10-26T02:30:00+0200», one hour earlier, would be a correct answer as well.

Источник

The DateTime class

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

Introduction

This class behaves the same as DateTimeImmutable except objects are modified itself when modification methods such as DateTime::modify() are called.

Class synopsis

Changelog

Table of Contents

User Contributed Notes 26 notes

Set Timezone and formatting.

= time ();
$timeZone = new \ DateTimeZone ( ‘Asia/Tokyo’ );

DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the ‘u’ format string.

// Instantiate a DateTime with microseconds.
$d = new DateTime ( ‘2011-01-01T15:03:01.012345Z’ );

There is a subtle difference between the following two statments which causes JavaScript’s Date object on iPhones to fail.

/**
On my local machine this results in:

Both of these strings are valid ISO8601 datetime strings, but the latter is not accepted by the constructor of JavaScript’s date object on iPhone. (Possibly other browsers as well)
*/

?>

Our solution was to create the following constant on our DateHelper object.

class DateHelper
<
/**
* An ISO8601 format string for PHP’s date functions that’s compatible with JavaScript’s Date’s constructor method
* Example: 2013-04-12T16:40:00-04:00
*
* PHP’s ISO8601 constant doesn’t add the colon to the timezone offset which is required for iPhone
**/
const ISO8601 = ‘Y-m-d\TH:i:sP’ ;
>
?>

Small but powerful extension to DateTime

class Blar_DateTime extends DateTime <

= new Blar_DateTime ( ‘1879-03-14’ );

Albert Einstein would now be 130 years old.

Albert Einstein would now be 130 Years, 10 Months, 10 Days old.

Albert Einstein was on 2010-10-10 131 years old.

Example displaying each time format:

$dateTime = new DateTime();

The above example will output:

At PHP 7.1 the DateTime constructor incorporates microseconds when constructed from the current time. Make your comparisons carefully, since two DateTime objects constructed one after another are now more likely to have different values.

This caused some confusion with a blog I was working on and just wanted to make other people aware of this. If you use createFromFormat to turn a date into a timestamp it will include the current time. For example:

if you’d like to print all the built-in formats,

This might be unexpected behavior:

#or use the interval
#$date1->add(new DateInterval(«P1M»));

#will produce 2017-10-1
#not 2017-09-30

A good way I did to work with millisecond is transforming the time in milliseconds.

function timeToMilliseconds($time) <
$dateTime = new DateTime($time);

If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:

$date = new DateTime(«2010-07-05T06:00:00Z», new DateTimeZone(«Europe/Amsterdam»));

will create a DateTime object set to «2010-07-05 06:00:00+0200» (+2 being the TZ offset for Europe/Amsterdam)

To get this done, you will need to set the timezone separately:

$date = new DateTime(«2010-07-05T06:00:00Z»);
$date->setTimeZone(new DateTimeZone(«Europe/Amsterdam»);

This will create a DateTime object set to «2010-07-05 08:00:00+0200»

It isn’t obvious from the above, but you can insert a letter of the alphabet directly into the date string by escaping it with a backslash in the format string. Note that if you are using «double» speech marks around the format string, you will have to further escape each backslash with another backslash! If you are using ‘single’ speech marks around the format string, then you only need one backslash.

For instance, to create a string like «Y2014M01D29T1633», you *could* use string concatenation like so:

please note that using

setTimezone
setTimestamp
setDate
setTime
etc..

$original = new DateTime(«now»);

so a datetime object is mutable

(Editors note: PHP 5.5 adds DateTimeImmutable which does not modify the original object, instead creating a new instance.)

Create function to convert GregorianDate to JulianDayCount

Note that the ISO8601 constant will not correctly parse all possible ISO8601 compliant formats, as it does not support fractional seconds. If you need to be strictly compliant to that standard you will have to write your own format.

Bug report #51950 has unfortunately be closed as «not a bug» even though it’s a clear violation of the ISO8601 standard.

It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like ‘EDT’, then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it. Take the following code:

Be aware that DateTime may ignore fractional seconds for some formats, but not when using the ISO 8601 time format, as documented by this bug:

$dateTime = DateTime::createFromFormat(
DateTime::ISO8601,
‘2009-04-16T12:07:23.596Z’
);
// bool(false)

Be aware of this behaviour:

In my opinion, the former date should be adjusted to 2014/11/30, that is, the last day in the previous month.

Here is easiest way to find the days difference between two dates:

If you’re stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:

If you need DateTime::createFromFormat functionality in versions class DateClass extends DateTime <

$regexpArray [ ‘Y’ ] = «(?P 19|20\d\d)» ;
$regexpArray [ ‘m’ ] = «(?P 09|1[012])» ;
$regexpArray [ ‘d’ ] = «(?P 04|[12]1|3[01])» ;
$regexpArray [ ‘-‘ ] = «[-]» ;
$regexpArray [ ‘.’ ] = «[\. /.]» ;
$regexpArray [ ‘:’ ] = «[:]» ;
$regexpArray [ ‘space’ ] = «[\s]» ;
$regexpArray [ ‘H’ ] = «(?P 08|18|23)» ;
$regexpArray [ ‘i’ ] = «(?P34)» ;
$regexpArray [ ‘s’ ] = «(?P53)» ;

Источник

Читайте также:  поздравление с новым годом и рождеством анимация
Образовательный портал