Convert javascript date to php date format - php

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.

Related

Carbon PHP parse datetime with dot notation

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, ['.' => '-']));

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"));

Convert and insert two date formats MYSQL

I'm facing an issue with managinging dates, some dates pass others dont. I want to produce an insertable date for mysql. there are two possible types of post dates
yyyy-mm-dd //should go without conversion
m/d/yyyy // should be converted
I'm using this
$date = $_REQUEST['date'];
$date_regex = '/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/';
if(preg_match($date_regex, $date)){
$date = DateTime::createFromFormat('m/d/Y',$date)->format('Y-m-d');}
problems
I realised this regex is failing for dates like
2/5/2013
but has been working for
12/12/2013
so I removed it BUT still
DateTime::createFromFormat('m/d/Y',$date)->format('Y-m-d');
is also failing for m/d/yyyy
This date thing has got my head spinning for the last 6 hours.
In this case, there is no need to use DateTime::createFromFormat because m/d/yyyy is one of the recognized date formats (see "American month, day and year"). Just convert it to a DateTime object and let the constructor handle the format and forget the regex:
$date = $_REQUEST['date'];
$datetime = new DateTime($date);
$datex = $datetime->format('Y-m-d');
The reason DateTime::createFromFormat('m/d/Y',$date) fails for dates like 2/5/2013 is because you are forcing it to be specifically 'm/d/Y' and that date does not fit that pattern. You can see a list of all date formats here. Specifically, m expects there to be a leading zero (like 02), so when you give it one without that, it won't recognize it. Same goes for d. In this case you would have to use n and j respectively. But, like I said, let the constructor do the hard work for you.

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.

How to parse any date format

I'm trying to make something clever in order to parse date in any international format.
On my frontend I use jquery ui as a date picker and each languages has its specific date format.
Fr: d/m/Y
En: m/d/Y
...
OK but now on the php part I have to store those date using the same format (Mysql Y-m-d). I would like to avoid using switch case and stuff like that so I started to look for another alternative.
The best thing I've found is
http://www.php.net/manual/en/datetime.createfromformat.php That function will enable me to parse the dates if I know the format.
For example
$format = 'Y-m-d';
$date = DateTime::createFromFormat($format, '2009-02-15');
Ok so that's a good start but now I'd like to find the standard date format for the current locale.
So I found this :
http://www.php.net/manual/en/intldateformatter.getpattern.php
But I dont really know how to get it to work because I get inconstitent results:
php > $i = new IntlDateFormatter("fr_FR.utf8",IntlDateFormatter::SHORT,IntlDateFormatter::NONE);
php > echo $i->getPattern();
dd/MM/yy
/* correct ! */
but
php > $i = new IntlDateFormatter("en_US.utf8",IntlDateFormatter::SHORT,IntlDateFormatter::NONE);
php > echo $i->getPattern();
M/d/yy /* wtf */
Am I missing something ?
Thanks
There is no "universal date format symbol standard". The symbol "y" could be a 2-digit year, a 4-digit year, or even a 3-letter abbreviated month (highly unlikely), depending on the source.
The formatting symbols for IntlDateFormatter are documented here. As you can see from the documentation, for this implementation, "d" is the date without leading zeros, while "dd" contains the leading zeros. Both "M" and "MM" represent the month with leading zeros. The "yy" is the 2-digit year.
There is enough difference between this and jQuery UI's date format symbols that you'll need a data map to map the IntlDateFormatter format symbols to jQuery UI datepicker format symbols, and vice versa.
Something like this should be sufficient (untested):
// PHP => jQuery
$formatMap = array(
'dd' => 'dd',
'd' => 'd',
'MM' => 'mm',
'M' => 'mm',
'yy' => 'y'
// and so on...
);
Once you have your map set up, you can create your IntlDateFormatter based on locale, convert that format's symbols into jQuery UI date format symbols, and then send the format to the front-end.
When the user posts back the chosen date, you can do the same in reverse to get back to IntlDateFormatter symbols. At that point, you can use a combination of IntlDateFormatter::setPattern() to set the format to MySQL-style, and datefmt_format() (or equivalent) to actually format the posted date.
Hope this helps.

Categories