How to convert dates to specific formats in php? - php

I'm having trouble converting dates to php, what conversion would this date be for first? 2021-10-04T09:49:50.636-04:00.
In the documentation this format is ISO 8601, but it doesn't look like ISO 8601.
Ex:
$today = date('Y-m-d h:i:s');
$format = new DateTime($today);
$expires = $format->format(DateTime::ISO8601);
echo $expires; //2021-10-04T09:49:50-0300
Are extremely different:
2021-10-04T09:49:50-0300 ISO 8601
2021-10-04T09:49:50.636-04:00 The format I don't know
How can I convert my current date date() to this format?:
2021-10-04T09:49:50.636-04:00

DateTime automatically recognizes many date formats. So also "2021-10-04T09: 49: 50.636-04: 00" (DateTime :: RFC3339_EXTENDED).
To create a DateTime object, you don't have to know the exact name.
$strDate = "2021-10-04T09:49:50.636-04:00";
$dt = new DateTime($strDate);
/*
DateTime::__set_state(array(
'date' => "2021-10-04 09:49:50.636000",
'timezone_type' => 1,
'timezone' => "-04:00",
))
*/
Creating a DateTime object for today 00:00 is also easy:
$dt = new DateTime('today');
Examples of special output formats:
echo $dt->format(DateTime::ISO8601)."<br>";
echo $dt->format(DateTime::RFC3339_EXTENDED)."<br>";
/*
2021-10-04T09:49:50-0400
2021-10-04T09:49:50.636-04:00
*/
If you want to know what is behind a class constant like DateTime::RFC3339_EXTENDED then let it show you with PHP:
echo DateTime::RFC3339_EXTENDED; //Y-m-d\TH:i:s.vP

Related

Is it safe to convert ISO datetime with strtotime

For example
strtotime("2018-12-06T09:04:55");
strtotime("2021-07-09T14:09:47.529751-04:00");
I read in the php manual that ISO dates should be avoided when using strtotime, why ?
Should I extract date time from the string before using strtotime.
strtotime() will convert a string WITHOUT a timezone indication as if the string is a time in the default timezone ( date_default_timezone_set() ). So converting a UTC time like '2018-12-06T09:04:55' with strtotime() actually yields a wrong result. In this case use:
<?php
function UTCdatestringToTime($utcdatestring)
{
$tz = date_default_timezone_get();
date_default_timezone_set('UTC');
$result = strtotime($utcdatestring);
date_default_timezone_set($tz);
return $result;
}
?>
If the date string contains a time zone, strtotime also takes this into account.
$strDate = "2018-12-06T09:04:55 UTC";
$ts = strtotime($strDate); // int(1544087095)
If the time zone is missing in the date string, the default time zone is used. My Timezone is "Europe/Berlin".
$strDate = "2018-12-06T09:04:55";
$ts = strtotime($strDate); // int(1544083495)
As a result, we get a different timestamp.
If I want to convert a date string from another time zone into a time stamp, then the best solution is to do it with the DateTime object. There I can enter the correct time zone in the 2nd parameter when creating the object.
$strDate = "2018-12-06T09:04:55";
$dt = new DateTime($strDate, new DateTimeZone('UTC'));
$ts = $dt->getTimeStamp(); // int(1544087095)
Important: If the date string contains a valid time zone, this has priority over the 2nd parameter.
$strDate = "2018-12-06T09:04:55 UTC";
$dt = new DateTime($strDate, new DateTimeZone('Europe/Berlin'));
/*
DateTime::__set_state(array(
'date' => "2018-12-06 09:04:55.000000",
'timezone_type' => 3,
'timezone' => "UTC",
))
*/
The DateTimeZone ('Europe/Berlin') is ignored here.
Since strtotime also accepts a time zone in the date string, the time zone can also be added with a string concatenation.
$strDate = "2018-12-06T09:04:55";
$ts = strtotime($strDate." UTC"); //int(1544087095)
The UTCdatestringToTime function does the same. However, it is not nice to temporarily change the default time zone in the PHP script.

DateTime function unix timestamp converting wrong

I am using DateTime function of php. I get a date from a calendar in format d-m-Y and pass it via ajax to my function. I am getting the date right till this step.
When I try to store the date in unix format using:
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y', $data['date']);
$final_date=$ai_ff_date->format('U');
The date stored is wrong. Suppose the date I passed via ajax is 26-12-2016 then in database 27-12-2016 is stored. Why its counting one more day then the input.
use this code :
$date = date('Y-m-d H:i:s', strtotime('-1 day', $stop_date));
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y',$date);
$final_date=$ai_ff_date->format('U');
and please check the variable (code not tested)
You might want to convert the Date-Format to "Y-m-d" First and then call-in the DateTime() Constructor. However, since what you are trying to do is just get the TimeStamp you might also do that directly without using DateTime. The Snippet below shows what is meant here:
<?php
$data = ['date'=>"13-12-2016"]; //<== JUST AN EXAMPLE FOR TESTING!!!
// SIMPLY CONVERT THE DATE TO Y-m-d FIRST.
$dateYMD = date("Y-m-d", strtotime($data['date']));
// THEN USE DateTime CONSTRUCTOR TO CREATE A NEW DateTime INSTANCE
// AND THEN RUN THE FORMAT YOU WISH::
$final_date = (new DateTime($dateYMD))->format('U');
var_dump($final_date); //<== YIELDS: string '1481583600' (length=10)
var_dump(date("Y-m-d", $final_date)); //<== YIELDS: string '2016-12-13' (length=10)

How to convert a PHP DateTime object to ISO string?

I have a date that I receive in MS format for JSON dates. It looks like this:
/Date(1365004652303)/
I can convert it to a PHP DateTime object by doing this:
$timestamp = round(((int) $originalMSdate) / 1000);
$convertedDate = new DateTime();
$convertedDate->setTimestamp($timestamp);
Ultimately, though, I need it to be a string in ISO 8601 format. I tried then converting it to an ISO date object & then converting that to a string with strval() but strval() doesn't work on date objects.
I've also tried
$dateString = date_format($convertedDate, 'YY-MM-DD H:i:s');
but I need it to also include timezone info, like this: 2015-10-01T21:22:57.057Z
I don't see characters for that in date_format.
How can I achieve this?
EDIT: I should clarify that I'm not printing the resulting string. I need to pass it to a field in a database that accepts a string datatype.
Please try the below code
<?php
// input
$time = microtime(true);
// Determining the microsecond fraction
$microSeconds = sprintf("%06d", ($time - floor($time)) * 1000000);
// Creating DT object
$tz = new DateTimeZone("Etc/UTC");
$dt = new DateTime(date('Y-m-d H:i:s.'. $microSeconds, $time), $tz);
$iso8601Date = sprintf(
"%s%03d%s",
$dt->format("Y-m-d\TH:i:s."),
floor($dt->format("u")/1000),
$dt->format("O")
);
// Formatting according to ISO 8601-extended
var_dump(
$iso8601Date
);
This worked:
$timestamp = round(((int) $originalMSdate) / 1000);
$dateString = date('c', $timestamp);
The format isn't EXACTLY the same. It's in this format:
2016-04-25T14:27:00-05:00 rather than
2016-04-25T14:27:00.057Z
but it's close enough that I can do some manipulation to get what I need.
this one is worked for me. For more please refer this article.
$date = date('Y-m-d H:m:s');
echo date('c', strtotime($date)); // 2020-04-08T16:04:56+05:30
echo date(DateTime::ISO8601, strtotime($date)); // 2020-04-08T16:04:56+0530
echo date(DateTime::ATOM, strtotime($date)); // 2020-04-08T16:04:56+05:30

Format Datetime class to '2013-08-05T10:00:00 '

I am using Datetime class on PHP.
you can change datetimeclass to string like this.
$date->format('Y-m-d H:i:s')
// it shows 2013-08-05 10:00:00
but somehow ,Google API requires format like this .
2013-08-05T10:00:00
What this T means ?
and How can I make this style string from DateTime class neatly?
The time is in ISO 8601 format. To print it out, you can use 'c' format character:
$date->format('c')
You could use jh314's solution above, and it will give you the time in following format:
2013-08-08T10:18:15+05:30
However, to format it exactly like you want, you could use the following:
$part1 = $date->format('Y-m-d'); // 2013-08-08
$part2 = $date->format('H:i:s'); // 10:19:37
$newdate = "{$part1}T{$part2}"; // 2013-08-08T10:19:37
Or better yet:
$date = $date->format('Y-m-d\TH:i:s'); // 2013-08-08T10:19:37
Ta-dah!
This is ISO 8601 datetime format check this
$date->format('c') //Output 2004-02-12T15:19:21+00:00
This is almost, but not quite ISO8601 format, so you need to format the output like this:-
$date = new \DateTime();
echo $date->format('Y-m-d\TH:i:s');
The \ escapes the 'T'. See the manual about formatting dates.
See it working

Date conversion and updating mongodb document using PHP

Progress :
1. I retireved date from a collection.
Example format : Fri Oct 05 14:59:31 +0000 2012
2. I was able to change its format.
CODE USED :
$cur=$col->find(array(),array("created_at"=>1,"_id"=>0));
// created_at = contains Date value
$cur_all=$col->find();
while($doc=$cur_all->getNext())
{
$doc2=$cur->getNext();
$pieces = implode(" ", $doc2);
//converted the array to string with space delimiting
if($pieces!=NULL)
{
$date1 = date_create_from_format("D M d G:i:s +O Y", $pieces);
echo date_format ( $date1 , 'Y-m-d G:i:s' );
//This is the format i would like to update in mongodb..
$filter = array('_id'=>new MongoId($doc['_id']));
$update = array('$set'=>array('created_at'=> newMongoDate($date2)));
$col->update($filter,$update);
}
}
QUESTION :
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
P.S : I did a lot of research on Stackoverflow (And other places, as well.) but I could not come to any conclusions. That is why this question. Let me know if there are any clarifications
Hmm even though you have explained your background well your actual question:
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
Is a bit confusing.
MongoDB will always save the date in one format and one format only when using ISODate: http://en.wikipedia.org/wiki/ISO_8601 (otherwise known as MongoDate in PHP) and it is probably best to not mess with this status quo.
So I would recommend you use the format Y-m-d G:i:s only as display, i.e.:
$date1 = new MongoDate();
var_dump(date('Y-m-d G:i:s', $date1->sec));
And you use the original $date1 object to actually save to the database.
Of course this would change if you were to create a date in your specified format however here is a piece of code for an example:
$date1 = new MongoDate();
$date2 = new MongoDate(strtotime(date ( 'Y-m-d G:i:s', $date1->sec )));
var_dump(date('Y-m-d G:i:s', $date2->sec));
You can use the $date2 as the date to save into MongoDB formed from the specific format you want.
look at http://php.net/manual/en/class.mongodate.php
your code should create a date using a unix timestamp
$date2 = ('23rd April 2013');
$update = array('$set'=>array(
'created_at'=> new MongoDate(strtotime($date2))
));
http://www.php.net/manual/en/function.strtotime.php

Categories