PHP : Function to convert the date format [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert one date format into another in PHP
I want to convert the date format from a particular format to some other.
For example,
Convert the date from ( 2011-06-21 or 2011/06/21 or 06/21/2011 ) to 21062011.
Is there any function to do this job.
Thanks in advance.

var_dump(
date('dmY', strtotime('2011-06-21')),
date('dmY', strtotime('2011/06/21')),
date('dmY', strtotime('06/21/2011'))
);

You should use the DateTime class.
$date = new DateTime('2011-06-21');
echo $date->format('dmY');
It can be used procedurally, if you wish.
var_dump(
date_format(date_create('2011-06-21'), 'dmY'),
date_format(date_create('2011/06/21'), 'dmY'),
date_format(date_create('06/21/2011'), 'dmY')
);

Hi you should be able to to use date combined with strtotime like so
$date; //the date that needs to be formatted
<?php date('dmY', strtotime($date)); ?>
So inside the date() function you simply format the date however you want the original date to be
php strtotime
Hope that helps

Unfortunately dates are very locale specific. strtotime() does not observe all of the niceties of the locale (and date_parse is a simple wrapper around strtotime). e.g. today is 21/06/2011 in the UK, and 06/21/2011 in the US.
A more robust solution is to use the DateTime class and its createFromFormat method.
However, IME, unless you are sourcing the input data from a consistent machine generated source, a better solution is to use a tool which facilitates input in a consistent format

Related

How do you format date as the following example: 2021-08-17T10:19:02.019Z in PHP [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 12 months ago.
I have use PHP to convert a simple datetime from MySQL
example: 2022-02-21 10:26:27
to a format like this one:
2021-08-17T10:19:02.019Z.
What function and formatting pattern should I use?
Also, could you please help me understand what the .019Z stand for?
Thank you!
EDIT:
Using echo date("c"); results in an output like this one: 2022-02-21T14:14:22+01:00, which differs form the desired output in the latest part (milliseconds and timezone).
On the other hand, if I do echo date("Y-m-d\TH:i:s.v"); I get an output like the following: 2022-02-21T14:22:24.000, where I should only be missing the timezone. I am not able to find it in the documentation.
The server isn't on the standard timezone, and I would like not to change it. Is there a way to get it dynamically?
The format you're looking for is ISO8601.
You can use the defined constants in DateTime object in PHP:
echo $objDateTime->format('c');
echo $objDateTime->format(DateTime::ISO8601);
See also DateTime formats in PHP documentation and the DateTime class itself
DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_format — Returns date formatted according to given format
https://www.php.net/manual/en/datetime.format.php

How to format an UTC date to use the Z (Zulu) zone designator in php?

I need to display and handle UTC dates in the following format:
2013-06-28T22:15:00Z
As this format is part of the ISO8601 standard I have no trouble creating DateTime objects from strings like the one above. However I can't find a clean way (meaning no string manipulations like substr and replace, etc.) to present my DateTime object in the desired format. I tried to tweak the server and php datetime settings, with little success. I always get:
$date->format(DateTime::ISO8601); // gives 2013-06-28T22:15:00+00:00
Is there any date format or configuration setting that will give me the desired string? Or I'll have to append the 'Z' manually to a custom time format?
No, there is no special constant for the desired format. I would use:
$date->format('Y-m-d\TH:i:s\Z');
But you will have to make sure that the times you are using are really UTC to avoid interpretation errors in your application.
If you are using Carbon then the method is:
echo $dt->toIso8601ZuluString();
// 2019-02-01T03:45:27Z
In PHP 8 the format character p was added:
$timestamp = new DateTimeImmutable('2013-06-28T22:15:00Z');
echo $timestamp->format('Y-m-d\TH:i:sp');
// 2013-06-28T22:15:00Z
In order to get the UTC date in the desired format, you can use something like this:
gmdate('Y-m-d\TH:i:s\Z', $date->format('U'));
To do this with the object-oriented style date object you need to first set the timezone to UTC, and then output the date:
function dateTo8601Zulu(\DateTimeInterface $date):string {
return (clone $date)
->setTimezone(new \DateTimeZone('UTC'))
->format('Y-m-d\TH:i:s\Z');
}
Edit: clone object before changing timezone.
Since PHP 7.2 DateTimeInterface::ATOM was introduced in favor of DateTimeInterface::ISO8601, although it still lives on for backward compatability reasons.
Usage
$dateTimeObject->format(DateTimeInterface::ATOM)

PHP DateTime will not allow a date format [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
strtotime failing on mm-dd-yyyy hh:mm
I have a date coming in like shown below but the DateTime function will not allow it:
$start = new DateTime('13/10/2012');
echo $start->format("Y-m-d");
It allows all other methods, even using '10/13/2012' but I can't change it because that's the format i'm receiving the date in.
Any ideas?
Thanks
Did you try, createFromFormat() ?
$start = DateTime::createFromFormat('d/m/Y', '13/10/2012');
try DateTime::createFromFormat like
$start = DateTime::createFromFormat('d/m/Y', '13/10/2012');
According to the documentation, it only accepts dates in specific formats, one of them is "american month, day, year", which will obviously fail if you provide 13 as the month.
I always try to avoid working with dates in ambiguous formats. Mostly using "2012-10-13" within the code, and "13 Oct, 2012" for user-facing dates. Both can be parsed reliably by any date formatting API I've got experience with.
But when forced to work with an ambiguous format, I parse it manually instead of relying on PHP's built in API, since I fully understand what it's going to do. For example:
list($day, $month, $year) = preg_split('/[^0-9]+/', '13/10/2012');
$start = new DateTime("$year-$month-$day");

PHP Zend date format

I want to input a timestamp in below format to the database.
yyyy-mm-dd hh:mm:ss
How can I get in above format?
When I use
$date = new Zend_Date();
it returns month dd, yyyy hh:mm:ss PM
I also use a JavaScript calender to insert a selected date and it returns in dd-mm-yyyy format
Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. Because date format not matching the database field format the date is not inserted and only filled with *00-00-00 00:00:00*
Thanks for answer
Not sure if this will help you, but try using:
// to show both date and time,
$date->get('YYYY-MM-dd HH:mm:ss');
// or, to show date only
$date->get('YYYY-MM-dd')
Technically, #stefgosselin gave the correct answer for Zend_Date, but Zend_Date is completely overkill for just getting the current time in a common format. Zend_Date is incredibly slow and cumbersome to use compared to PHP's native date related extensions. If you don't need translation or localisation in your Zend_Date output (and you apparently dont), stay away from it.
Use PHP's native date function for that, e.g.
echo date('Y-m-d H:i:s');
or DateTime procedural API
echo date_format(date_create(), 'Y-m-d H:i:s');
or DateTime Object API
$dateTime = new DateTime;
echo $dateTime->format('Y-m-d H:i:s');
Don't do the common mistake of using each and every component Zend Frameworks offers just because it offers it. There is absolutely no need to do that and in fact, if you can use a native PHP extension to achieve the same result with less or comparable effort, you are better off with the native solution.
Also, if you are going to save a date in your database, did you use any of the DateTime related columns in your database? Assuming you are using MySql, you could use a Timestamp column or an ISO8601 Date column.
This is how i did it:
abstract class App_Model_ModelAbstract extends Zend_Db_Table_Abstract
{
const DATE_FORMAT = 'yyyy-MM-dd';
public static function formatDate($date, $format = App_Model_ModelAbstract::DATE_FORMAT)
{
if (!$date instanceof Zend_Date && Zend_Date::isDate($date)) {
$date = new Zend_Date($date);
}
if ($date instanceof Zend_Date) {
return $date->get($format);
}
return $date;
}
}
this way you don't need to be concerned with whether or not its actually an instance of zend date, you can pass in a string or anything else that is a date.
a simple way to use Zend Date is to make specific function in its business objects that allows to parameter this function the date format. You can find a good example to this address http://www.pylejeune.fr/framework/utiliser-les-date-avec-zend_date/
this is i did it :
Zend_Date::now->toString('dd-MM-yyyy HH:mm:ss')
output from this format is "24-03-2012 13:02:01"
and you can modified your date format
I've always use $date->__toString('YYYY-MM-dd HH-mm-ss'); method in the past but today didn't work. I was getting the default output of 'Nov 1, 2013 12:19:23 PM'
So today I used $date->get('YYYY-MM-dd HH-mm-ss'); as mentioned above. Seems to have solved my problem.
You can find more information on this on output formats here: http://framework.zend.com/manual/1.12/en/zend.date.constants.html

Function to parse psql timestamp

I display the date or the time on my website a lot and I'm thinking about writing a function to parse a PostgreSQL timestamp.
The timestamp is in the format: Y-m-d H:i:s.u. E.g. 2011-04-08 23:00:56.544.
I'm thinking about something like this:
function parse_timestamp($timestamp, $format = 'd-m-Y')
{
// parse the timestamp
return $formatted_timestamp;
}
However I am wondering whether this can also be achieved without writing a parser for it myself (with the use of some PHP function).
function parse_timestamp($timestamp, $format = 'd-m-Y')
{
return date($format, strtotime($timestamp));
}
Don't forget to set timezone before, e.g.
date_default_timezone_set('UTC');
Or in your case, I guess 'Europe/Amsterdam'.
You can always get PHP timestamp of this format Y-m-d H:i:s.u using strtotime(). Then, using date() you can export time in your own format. Both functions depend of time zone set.
strtotime is perfectly capable of parsing that time string, then just reformat it with date:
echo date('d-m-Y', strtotime('2011-04-08 23:00:56.544')); // 08-04-2011
For those using DateTime class:
DateTime::createFromFormat('Y-m-d H:i:s.u', $yourTime);
If the database isn't giving you what you want, change it. PostgreSQL can also format dates and times.
select to_char(timestamp '2011-03-04 07:04:00', 'DD-MM-YYYY');
04-03-2011
But that's risky in international contexts, like the web. Different locales expect different ordering of elements. (Does "04-03" mean 03-April or 04-March?) This expression is easier to understand, and it uses locale-specific abbreviations for the months.
select to_char(timestamp '2011-03-04 07:04:00', 'DD-Mon-YYYY');
04-Mar-2011
Take a look at the strptime function - it can parse many time formats.

Categories