php convert date format
PHP convert date format dd/mm/yyyy => yyyy-mm-dd [duplicate]
Any help will be greatly appreciated.
5 Answers 5
Use the default date function.
EDIT I just tested it, and somehow, PHP doesn’t work well with dd/mm/yyyy format. Here’s another solution.
If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.
Here’s another solution not using date(). not so smart:)
But make sure ‘dd/mm/yyyy’ is the actual date.
I can see great answers, so there’s no need to repeat here, so I’d like to offer some advice:
I would recommend using a Unix Timestamp integer instead of a human-readable date format to handle time internally, then use PHP’s date() function to convert the timestamp value into a human-readable date format for user display. Here’s a crude example of how it should be done:
This way you’ll avoid much headache dealing with date formats, conversions and timezones, as your dates will be in a standardized format (Unix Timestamp) that is compact, timezone-independent (always in UTC) and widely supported in programming languages and databases.
Php convert date format
(PHP 4, PHP 5, PHP 7, PHP 8)
date — Форматирует вывод системной даты/времени
Описание
Список параметров
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание |
---|---|
8.0.0 | timestamp теперь допускает значение null. |
Примеры
Пример #1 Примеры использования функции date()
// установка часового пояса по умолчанию.
date_default_timezone_set ( ‘UTC’ );
// выведет примерно следующее: Monday
echo date ( «l» );
// выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );
/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );
Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.
Пример #2 Экранирование символов в функции date()
Пример #3 Пример совместного использования функций date() и mktime()
Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.
Пример #4 Форматирование с использованием date()
// Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера,
// и мы находимся в часовом поясе Mountain Standard Time (MST)
$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 (формат MySQL DATETIME)
?>
Примечания
Смотрите также
User Contributed Notes 20 notes
Things to be aware of when using week numbers with years.
Conclusion:
if using ‘W’ for the week number use ‘o’ for the year.
In order to define leap year you must considre not only that year can be divide by 4!
The correct alghoritm is:
if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)
So the code should look like this:
For Microseconds, we can get by following:
echo date(‘Ymd His’.substr((string)microtime(), 1, 8).’ e’);
FYI: there’s a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:
echo date ( ‘Y-m-d\TH:i:sO’ );
?>
You can use
echo date ( DateTime :: ISO8601 );
?>
instead, which is much easier to read.
this how you make an HTML5 tag correctly
It’s common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP’s built-in functions. Consider http://php.net/manual/en/function.date.php#108613
date() will format a time-zone agnostic timestamp according to the default timezone set with date_default_timezone_set(. ). Local time. If you want to output as UTC time use:
$tz = date_default_timezone_get ();
date_default_timezone_set ( ‘UTC’ );
For HTML5 datetime-local HTML input controls (http://www.w3.org/TR/html-markup/input.datetime-local.html) use format example: 1996-12-19T16:39:57
To generate this, escape the ‘T’, as shown below:
If timestamp is a string, date converts it to an integer in a possibly unexpected way:
The example below formats today’s date in three different ways:
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
At least in PHP 5.5.38 date(‘j.n.Y’, 2222222222) gives a result of 2.6.2040.
So date is not longer limited to the minimum and maximum values for a 32-bit signed integer as timestamp.
Prior to PHP 5.6.23, Relative Formats for the start of the week aligned with PHP’s (0=Sunday,6=Saturday). Since 5.6.23, Relative Formats for the start of the week align with ISO-8601 (1=Monday,7=Sunday). (http://php.net/manual/en/datetime.formats.relative.php)
This can produce different, and seemingly incorrect, results depending on your PHP version and your choice of ‘w’ or ‘N’ for the Numeric representation of the day of the week:
Prior to PHP 5.6.23, this results in:
Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 10 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 10 Oct 2016
Since PHP 5.6.23, this results in:
Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 03 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 03 Oct 2016
I’ve tested it pretty strenuously but date arithmetic is complicated and there’s always the possibility I missed something, so please feel free to check my math.
The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. «skip all Fridays and Saturdays but include Sundays») or to set up dates that should always be skipped (e.g. «skip July 4th in any year, skip the first Monday in September in any year»). But that’s a project for another time.
$start = strtotime ( «1 January 2010» );
$end = strtotime ( «13 December 2010» );
// Add as many holidays as desired.
$holidays = array();
$holidays [] = «4 July 2010» ; // Falls on a Sunday; doesn’t affect count
$holidays [] = «6 September 2010» ; // Falls on a Monday; reduces count by one
?>
Or, if you just want to know how many work days there are in any given year, here’s a quick function for that one:
Convert one date format into another in PHP
Is there a simple way to convert one date format into another date format in PHP?
But I’d of course like it to return a current date rather than the crack ‘o dawn. What am I doing wrong?
17 Answers 17
The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can’t recognize.
You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn’t recognize the y-m-d-h-i-s format.
PHP 5.3 and up
PHP 5.2 and lower
You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.
The easiest way to do this is
This also avoids the use of strtotime, which can be hard to work with at times.
If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it’s even easier:
This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.
The Basics
Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.
Using DateTime()
As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:
Working with Unix timestamps
date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:
DateTime() works with Unix timestamps by adding an @ before the timestamp:
If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There’s two ways to do this:
Trimming the last three digits can be acheived several ways, but using substr() is the easiest:
You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:
To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:
If you’re running PHP 5.2 you can use the U formatting option instead:
Working with non-standard and ambiguous date formats
Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.
In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:
Convert a date format in PHP [duplicate]
I am trying to convert a date from yyyy-mm-dd to dd-mm-yyyy (but not in SQL); however I don’t know how the date function requires a timestamp, and I can’t get a timestamp from this string.
How is this possible?
18 Answers 18
Use strtotime() and date() :
(See the strtotime and date documentation on the PHP site.)
Note that this was a quick solution to the original question. For more extensive conversions, you should really be using the DateTime class to parse and format 🙂
If you’d like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,
Or if the source-format always is «Y-m-d» (yyyy-mm-dd), then just use DateTime:
Without the date conversion overhead, I am not sure it’ll matter much.
This code works for every date format.
Also another obscure possibility:
I don’t know if I would use it but still 🙂
Note: Because this post’s answer sometimes gets upvoted, I came back here to kindly ask people not to upvote it anymore. My answer is ancient, not technically correct, and there are several better approaches right here. I’m only keeping it here for historical purposes.
Although the documentation poorly describes the strtotime function, @rjmunro correctly addressed the issue in his comment: it’s in ISO format date «YYYY-MM-DD».
Also, even though my Date_Converter function might still work, I’d like to warn that there may be imprecise statements below, so please do disregard them.
The most voted answer is actually incorrect!
The PHP strtotime manual here states that «The function expects to be given a string containing an English date format». What it actually means is that it expects an American US date format, such as «m-d-Y» or «m/d/Y».
I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I’d be glad if that would be shared.
date — Форматирует вывод системной даты/времени
Описание
Список параметров
Шаблон результирующей строки ( string ) с датой. См. параметры форматирования ниже. Также существует несколько предопределенных констант даты/времени, которые могут быть использованы вместо этих параметров. Например: DATE_RSS заменяет шаблон ‘D, d M Y H:i:s’.
Возвращаемые значения
Ошибки
Список изменений
Версия | Описание |
---|---|
5.1.0 | Допустимым диапазоном дат для временных меток обычно являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Они соответствуют минимальному и максимальному значению 32-битного целого числа со знаком). Однако для PHP версии ниже 5.1.0 в некоторых операционных системах (например, Windows) этот диапазон был ограничен датами 01-01-1970 до 19-01-2038. |
5.1.0 |