Convert and insert two date formats MYSQL - php

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.

Related

Parse date with 7 digits in microseconds part

I'm trying to parse Atom feed and it contains date like this one
2019-02-28T06:11:12.0775241Z
The problem with it is microseconds 0775241, which is 7 digits, but php can handle only 6 digits. This date is probably generated with Go lang.
If it had 6 digits, Y-m-d\TH:i:s.u\Z would work fine.
UPD: it is for DateTime::createFromFormat, can't use new DateTime etc.
Looking for solution, may be you had same problem as me.
That is a standard easily recognisable date format. Use the DateTime class
$d = new DateTime("2019-02-28T06:11:12.0775241Z");
echo $d->format('d/m/y H:i:s');
RESULT
28/02/19 06:11:12
Of course you can output in any format you like
I know this is not the best solution but you can handle it with Carbon
$datetime = Carbon::parse('2019-03-13T18:07:54.5810814+03:30');
dump($datetime);
// Carbon #1552487874 {#358
// date: 2019-03-13 18:07:54.581081 +03:30
// }

separating a weird formatted timestamp into an understandable date

I'm working with an XML document that is returning variables and for some reason in a xml return the timestamp is formatted like this... 20180606T110000 ... why anyone would format it like that makes no sense to me; however, its what I have to work with. ITs formatted YYYYMMDD , the T is the split between date and time, HHMMSS. ITs set up in a 24 Hour clock that I also need to convert to 12 hr clock with am/pm
I need that formatted like 06/06/2018 11:00:00 AM.
Is there a way to do that via a date format (I know how to use date() but I don't know how to bring in that timestamp the way its formatted) or even separating it out into
$year = xxxx
$month = xx
$day = $xx
$Hour=xx
etc. etc. etc.
if need be.
I've briefly looked at php's date create from format ( date_create_from_format('j-M-Y', '15-Feb-2009') ) but dont fully understand how that works.
I've also thought about a split. I've also looked at chunk_split and wordwrap but its not even amounts of characters so that would be complex to create.
Any ideas?
The format you're working with is "XMLRPC (Compact)" format. This is fully supported by PHP (you can see a list of supported formats here). To get what you want, just use a combination of strtotime() and date().
$timestring = "20180606T110000";
$timestamp = strtotime($timestring);
echo date("m/d/Y h:i:s A", $timestamp);
You can use PHP DateTime to parse a datetime String with any format. Please view the Parameters format in the following link to understand how the "Ymd\THis" part works: http://php.net/manual/en/datetime.createfromformat.php
<?php
$time = "20180606T110000";
$date = DateTime::createFromFormat("Ymd\THis", $time);
// 06/06/2018 11:00:00 AM.
echo $date->format("d/m/Y h:i:s A");

Converting date in specific format to unix then comparing

I'm having problems comparing two dates in PHP. I want to compare the current date to one entered by a user.
$date = "18/05/2018";
The date input by the user.
$date_unix = strtotime($date);
Used to convert the date from the given format to time, in order to be compared.
if($date_unix < time()){
echo '<b>Notice:</b> You cannot specify a date in the past.<br>';
}
The above if statement is always run and i'm confused as to why. Any help would be appreciated.
strtotime makes assumptions about the date format, and in this case those assumptions are wrong.
You are using a day/month/year format (like me: that's the default format in Italy). Yesterday, a date of 12/05/2018 would have been taken by strtotime, and assumed to be december 5th, 2018. The test would have been passed, and apparently been correct.
And if it had been a reservation, it would have incurred in seven months' worth of charges ;-D
So always specify the format. For that, I feel that the best is using DateTime:
$date = date_create_from_format('d/m/Y', '18/05/2018');
for the same reasons, be wary how you calculate date differences.
(Also, be wary of Daylight Saving Time).
From the strtotime documentation:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed
As 18/05/2018 is not a valid date in the American format (where the first number represents the month), your strtotime call will return false. And false (zero) will always be less than time().
The simplest fix, if you are confident about the format of the input, would be to replace the slashes with dashes before converting to timestamp. strtotime will then interpret the string as an international date which will work correctly:
$date = str_replace('/', '-', "18/05/2018");
$date_unix = strtotime($date);
However, updating your code to use the DateTime class, as in smith or LSerni's answers, will probably give you more flexibility going forward.
should stop uing the legacy strtotime and start using the DateTime class
$date = "18/05/2018";
$newDate = DateTime::createFromFormat('d/m/Y', $date);
if (new DateTime() < $newDate) {
echo 'future';
}else{
echo 'past';
}
To fix this problem, using information provided above I used the explode() to split up the $date variable into an array then rearrange the resulting array. I then pieced the exploded variables back together to form the correct American date format.
Below is the code relating to the above description:
$splitdate = (explode("/",$date));
$splitdate_day = $splitdate[0];
$splitdate_month = $splitdate[1];
$splitdate_year = $splitdate[2];
$date_change = $splitdate_month . "/" . $splitdate_day . "/" . $splitdate_year;
if(strtotime($date_change) < time()){
echo '<b>Notice:</b> You cannot specify a date in the past.<br>';
}
This may not be the most efficent method, but it solved the issue I was encoutering.

PHP Date Formatting not working wen using date_format()

I have a date field I'm pulling from WordPress, where the default format is:
16/12/2016
Been a while since I played with PHP, but I remember the way to format dates was: echo date_format($date,"[format syntax]");
But when I do
$date = myWPField;
echo date_format($date,"F d, y");
If doesn't display the date.
What am I missing. Has this changed?
Since your date is not an acceptable format in date_create like mm/dd/yy(yy) or mm-dd-yy(yy)
Use php DateTime::createFromFormat function instead this function can detect what format you
(PHP 5 >= 5.3.0, PHP 7)
DateTime::createFromFormat -- date_create_from_format — Parses a time string according to a specified format
$date = '16/12/2016';
$show_date = DateTime::createFromFormat('d/m/Y', $date)->format('F d, y');
Demo
when create data format form string use slash format, it's in the mm/dd/yy(yy) format. So in you code your first 16 is not allowed by default, you have to specify in what format to create from the string.
Note that when you create a new date object using a format with slashes and dashes (eg 02-02-2012 or 02/02/2012) it must be in the mm/dd/yy(yy) or mm-dd-yy(yy) format (rather than british format dd/mm/yy)! Months always before years (the american style) otherwise you'll get an incorrect date and may get an error like the one above (where PHP is crashing on trying to decode a 13th month).

PHP week date conversion

My date formatted like this "2000-5-1". First digit represents 4 digit year. The second is number of week in year, and the last one represents number of day in week.
No matter what I do, function always returns false, my code is following:
date_create_from_format("Y-W-N", "2000-5-1")
(docs)
Please avoid solutions that are using magic words like "+1 day" etc.
Creating a DateTime object from a compound format with year/week/day is described in the compound formats section of the supported date and time formats section of the PHP Docs:
$x = new DateTime("2000-W05-1");
var_dump($x);
Note that the week number requires a leading zero
Result is a DateTime object for 2000-01-31
If you look at the documantation of DateTime::createFromFormat (which is what you are using with an alias) and date(), there is not a 100% overlap of the formats, so you have a problem.
This is what I found that you could use as an alternative: DateTime::setISODate
$date = explode('-','2000-5-1');
$newDate = new DateTime();
$newDate->setISODate($date[0], $date[1], $date[2]);
setISODate will take the year, week and day as explained in the documentation to create a DateTime object.

Categories