PHP converting date format - php

Duplicate
Managing date formats differences between PHP and MySQL
PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY?
Format DATETIME column using PHP after printing
date formatting in php
Dear All,
I have a PHP page where i wil be displaying some data from Mysql db.
I have 2 dates to display on this page.In my db table, Date 1 is in the format d/m/Y (ex: 11/11/2002) and Date 2 is in the format d-m-Y (ex : 11-11-2002)
I need to display both of this in the same format .The format i have stored in a variable $dateFormat='m/d/Y'
Can any one guide me
Thanks in advance

Use strtotime to convert the strings into a Unix timestamp, then use the date function to generate the correct output format.
Since you're using the UK date format "d/m/Y", and strtotime expects a US format, you need to convert it slighly differently:
$date1 = "28/04/2009";
$date2 = "28-04-2009";
function ukStrToTime($str) {
return strtotime(preg_replace("/^([0-9]{1,2})[\/\. -]+([0-9]{1,2})[\/\. -]+([0-9]{1,4})/", "\\2/\\1/\\3", $str));
}
$date1 = date($dateFormat, ukStrToTime($date1));
$date2 = date($dateFormat, ukStrToTime($date2));

You should be all set with this:
echo date($dateFormat, strtotime($date1));
echo date($dateFormat, strtotime($date2));

You may want to look into the strptime function. This can convert any date from a string back into numeric values. Unlike strtotime, it can be adapted to different formats, including those from different locales, and its output is not a UNIX timestamp, so it's capable of parsing dates before 1970 and after 2037. It may be a little bit more work though because it returns an associative array though.
Unfortunately it's not available on Windows systems either so it's not portable.

If for some reason strtotime will not work for you, could always just replace the offending punctuation with str_replace.
function dateFormat($date) {
$newDate = str_replace(/, -, $date);
echo $newDate;
}
echo dateFormat($date1);
echo dateFormat($date2);
I know this will make most folks cringe, but it may help you with formatting non-date strings in the future.

rookie i am. so came up with the method that just do that. what mysql needs.. shish i used param 2... hope it helps. regards
public function dateConvert($date,$param){
if($param==1){
list($day,$month,$year)=split('[/.-]',$date);
$date="$year-$month-$day"; //changed this line
return $date;
}
if ($param == 2){ //output conversion
list($day,$month,$year) = split('[/.]', $date);
$date = "$year-$day-$month";
return $date;
}
}

Related

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

False dateresult using date() php

I want to parse the date 1938 1938+02:00 using date() & strtotime().
My code:
echo date("Y", strtotime("1938+02:00"));
gives me as result "2014"..
What am i doing wrong?
For something like this just get the first four characters of the string. No need to work with dates and such:
echo substr('1938+02:00', 0, 4);
Demo
But if you insist on using date functionality you'll need to use DateTime::createFromFormat() as that date string is not a standard format.
$date = DateTime::createFromFormat('YP', '1938+02:00');
echo $date->format('Y');
Demo
date("Y"); only return the year. That's what the Y does.
See the Manual page for date for other options.
EDIT
Another thing to consider, is that timestamps only go back to 1970. That's what a timestamp is (the number of seconds since 1970).
So, that's going to give you a negative value for the timestamp.
Your date string is not in an acceptable format. here is a list of acceptable formats for strtotime

strtotime() does not return correct value when specifying date in dd/mm/yyyy format

I want to convert date 24/09/2010 in format dd/mm/yyyy to 2010-09-24 in format yyyy-mm-dd.
This works:
date("Y-m-d",strtotime("09/24/2010"));
But this does not:
date("Y-m-d",strtotime("24/09/2010")); // it returns '1970-01-01'
Any idea why?
according to php, the valid php formats are stated here. So basically what you gave is invalid.
Alternatively, you can use mktime, date_parse_from_format or date_create_from_format
strtotime does its best to guess what you mean when given a string, but it can't handle all date formats. In you example, it is probably thinking that you are trying to refer to the 24th month, which isn't valid, and returns 0, which date then treats as the unix epoch (the date you got).
you can get around this using the mktime() and explode() functions, like so:
$date = "24/09/2010";
$dateArr = explode("/",$date);
$timeStamp = mktime(0,0,0,$dateArr[1],$dateArr[0],$dateArr[2]);
$newFormat = date("Y-m-d",$timeStamp);
As you say,
date("Y-m-d",strtotime("09/24/2010"))
will work,because the date format--"09/24/2010"is correct,
but "24/09/2010" is not the correct date format.
you can find something useful here

Categories