Carbon PHP parse datetime with dot notation - php

I'm using Carbon 2 and am having an issue with some strange dates in my application that are given to me by a third party api, ideally they'd always be in the YYYY-MM-DD format but a few are coming in the following format: YYYY.MM.DD.
How can I use Carbon::parse() or PHP to reliably convert the string to hyphens and then parse it if in that format?
Example:
echo Carbon::parse('2022.07.24 10:34:05');
This is invalid.
Maybe I just look for the dots and change to hyphen and try re-parsing?

As described in the documentation:
$date = Carbon::createFromFormat('Y.m.d H:i:s', '2022.07.24 10:34:05');

In your case, you can normalize the string before the parse():
$str = '2022.07.24 10:34:05'; // or '2022-07-24 10:34:05'
echo Carbon::parse(strtr($str, ['.' => '-']));

Related

PHP convert string into date time

I have a php string from db it is 20/11/2017 I want to convert it milliseconds.
It's my code to doing that.
$the_date = "20/11/2017";
$mill_sec_date = strtotime($the_date);
var_dump($mill_sec_date);
But it does not print any thing rather than
bool(false);
What is the problem and how can i solve it ????
When using slashes to separate parts of the date, PHP recognizes the format as MM/DD/YYYY. Which makes your date invalid because there is no 20th month. If you want to use the format where day and month is swapped, you need to use hyphens, like DD-MM-YYYY.
$time = strtotime('10/16/2003');
$newformat = date('Y-m-d',$time);
print_r($newformat);
Use DateTime class to call function createFromFormat
$date = date_create_from_format('d/M/Y:H:i:s', $string);
$date->getTimestamp();
Most likely you got the date format wrong, see
here for a list of supported date and time formats:
This section describes all the different formats that the strtotime(), DateTime and date_create() parser understands.
You string is not accept by the strtotime, you can use createFromFormat set set the with the format type of the time string like below, you can also check the live demo. And you also can refer to this answer
var_dump(DateTime::createFromFormat('d/m/Y', "20/11/2017"));

RFC 3339 how make a dateTime from

I'm trying to format a date passed from a google plus Api thats like the guide says in RFC 3339 format:
PUBLISHED-> datetime-> The time at which this activity was initially published. Formatted as an RFC 3339 timestamp.
So by php documentation i found that:
DATE_RFC3339
Same as DATE_ATOM (since PHP 5.1.3)
And that both format are something like:
"Y-m-d\TH:i:sP"
Actually the output of the Google api is something like:
2014-01-22T10:36:00.222Z
When I'm trying to launch command like:
$date = DateTime::createFromFormat("Y-m-d\TH:i:sP", $activity['published']); //$activity['published'] contain the date
I have always FALSE as return.
In my opinion the problem is in the final part
.222Z
any suggestion will be appreciate before cutting it by some rudimental approach...
You don't need to use DateTime::createFromFormat() for standard inputs. Just use:
$date = new DateTime('2014-01-22T10:36:00.222Z');
var_dump($date);
But if you still insist to use createFromFormat(), then use correct format, with microseconds:
$date = DateTime::createFromFormat('Y-m-d\TH:i:s.uP', '2014-01-22T10:36:00.222Z');
var_dump($date);
There is a trick. A special constant DATE_RFC3339 was made to help, but it does not work if the last character is "Z" - which is perfectly fine for rfc3339 format. Actually JSON would specify format like that:
expected format YYYY-MM-DDThh:mm:ssZ or YYYY-MM-DDThh:mm:ss+hh:mm
But using this DATE_RFC3339 you can receive an Error message from PHP:
InvalidArgumentException: The timezone could not be found in the database
That is why we need to specify format manually:
With DateTime
$date = DateTime::createFromFormat ('Y-m-d\TH:i:s.u\Z', $time);
With Carbon:
\Carbon\Carbon::createFromFormat('Y-m-d\TH:i:s.u\Z', $time);

How to format a PHP date in .Net DataContractJsonSerializer format?

There is a requirement to send a date inside a JSON post using PHP in this following format
\/Date(410256000000-0800)\/
How do I convert a standard dd-mm-yyyy h:i:s datetime like 01-01-2013 12:00:00 to that format in PHP? Just need to know what values correspond to what in that format, not really look for a stringify things answer.
This should do it:
$dateTime = DateTime::createFromFormat('d-m-Y H:i:s', '01-01-2013 12:00:00');
$requiredJsonFormat = sprintf(
'\/Date(%s%s)\/',
$dateTime->format('U') * 1000,
$dateTime->format('O')
);
echo $requiredJsonFormat; // prints '\/Date(1357038000000+0100)\/'
I leave it up to you to find what the formats U and O do from http://php.net/date.
An alternative would be to use PHP's DOTNET API and use the DataContractJsonSerializer class directly from PHP. However, you'd need .NET installed on the server and using PHP's DOTNET API is rather arcane.
The more interesting part is why you need this format at all. This is explained in a blogpost at http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx
But because of a strange oversight in the EcmaScript specs, there is no standard way of describing dates in JSON. […] Our current approach is using a small loophole in the JSON specs. In a JSON string literal, you may (or may not) escape some characters. Among those characters, weirdly enough, there is the slash character ('/'). […] The new format is "/Date(1198908717056)/" where the number is again the number of milliseconds since January 1st 1970 UTC […] The point is that this disambiguates a date literal from a string that looks like the same date literal, while remaining pure JSON that will be parsed by any standard JSON parser. Of course, a parser that doesn't know about this convention will just see a string, but parsers that do will be able to parse those as dates without a risk for false positives
We created a package for this: https://github.com/webapix/dot-net-json-date-formatter
It uses a similar approach than the previous answer, tested on PHP versions >= 5.6.
use DateTime;
use DateTimeZone;
use Webapix\DotNetJsonDate\Date;
$date = DateTime::createFromFormat(
'd-m-Y H:i:s',
'01-01-2013 12:00:00',
new DateTimeZone('+0000')
);
Date::toJsonDate($date); // returns '/Date(1357041600000+0000)/'

Convert javascript date to php date format

I'm using a jQuery datepicker where obviously the date format doesn't match php format.
How could I convert the datepicker format over to php format so that I can output date( $format ) in the same convention defined in the datepicker format. So say I put the format like dd/mm/yyyy, how could I convert that to m/d/o in php? Or if I specified it as d-m-yy, how to convert that to n-j-y?
Basically, wondering how I could convert the allowed date picker formats, regardless of what the letters or the separators are to php.
I've tried using preg_replace, but the issue there is with single and double same letters. dd becomes nn, since it's trying to replace d twice. Could something with regex be used maybe? I'm kind of lost on how the logic to convert would be done.
Edit: My Apologies for a oversight in the details. The js format is literally like dd/mm/yyyy, not the actual date output. What it is, in the CMS, the user defines the format the datepicker uses (dd/mm/yyyy or any other format sequence and separators the datepicker has). The PHP is used to output the current date using that defined format and sequence. I would love to have them define a PHP format and then convert that to the js format. But the powers that be always want things the way they want them - sigh).
Edit#2
Here's a working script up on Codepad, which shows the issue with letters in the format being treated individually and doubled up. mm becomes nn instead of just being m. The rest of the characters are being individualized as well.
http://codepad.org/lBgqVgbs
this is how would approach it:
$date = '13/06/2013';
$date = implode("-",array_reverse(explode("/",$date)));
$time = strtotime($date);
echo date("m-d-Y H:i:s",$time); // or however you want to format
explode the date by /
reverse the order of the array for proper strtotime() format
implode the pieces for our strtotime() string
You'll probably want to use DateTime::createFromFormat, which let's you define how a string is formatted. Then, use the format() function of that object to output the date in the way that you want it.
For example:
date_default_timezone_set('Europe/Berlin'); // or any other timezone - you must set a timezone though
$date = DateTime::createFromFormat('d/m/Y', '20/05/1996');
$formatted_date = $date->format('Y-m-d');
var_dump($formatted_date); // output: string(10) "1996-05-20"
You can use almost all of the same formatting letters as for the regular date() function, but if you need extra ones - for instance 'o', you can use the formatted date for that: $yet_another_date = date('m/d/o', strtotime($formatted_date));
Was actually easier than I thought it would be. I didn't know you could use #var#i. So mixing that into the two arrays and using preg_replace...
$pattern = array( '#mm#i', '#m#i', '#dd#i', '#d#i', '#yyyy#i', '#yy#i' );
$replacement = array( 'm', 'n', 'd', 'j', 'o', 'y' );
$date_format = preg_replace( $pattern, $replacement, $option_format );
Many thanks to those that provided answers to my bumbled question. My apologies.

Convert or Extract Year, Month and Date from a string in PHP

All,
I have the following string:
$dateTime = '2013-09-15T00:00:00.000Z';
Is there a function to extract Year, Month and Date from the above string, so the result looks like the following:
$yearMonthDate = '2013-09-15';
Thanks
You could convert your datetime to a timestamp using strtotime() and then convert it back into a formatted date using this kind of syntax:
date("Y-m-d", strtotime($myOriginalDate))
substr or DateTime or strtotime+date
Since the first string is actually a standard, you can just use substr:
$yearMonthDate = substr($dateTime, 0, 10);
However, that would be kind of a hack and would obviously break if the format of $dateTime were to change. So, you might want to look into the PHP DateTime class instead.

Categories