Re-Format Date with PHP - php

I have the following value in a variable: 26/03/2011
I'd like to get this in the format: 2011-03-26
How do I achieve this?
Many thanks

Try this:
list($d, $m, $y) = explode("/", "26/03/2011");
echo "$y-$m-$d";

While there are many ways to do this, I think the easiest to understand and apply to all date conversions is:
$date = date_create_from_format('d/n/Y', $date)->format('Y-n-d');
It is explicit and you'll never have to wonder about m/d or d/m, etc.

Might be a good idea to use the date() function combined with mktime():
$date = explode('/', '26/03/2011');
echo date('Y-m-d', mktime(0,0,0,$date[1],$date[0],$date[2]));
The reason why this could be a good idea is if you ever want to format the date in a different (more complex) format, say "March 26th, 2011" you could just do:
$date = explode('/', '26/03/2011');
echo date('F jS, Y', mktime(0,0,0,$date[1],$date[0],$date[2]));

Related

Change date format in php from string format to another in PHP

I need to change date format in php from 1/11/2020 (String format) to 2020-11-01
Thanks in advance
Regards,
Sathish
<?
$date = "1/11/2020";
$date = str_replace('/', '-', $date );
$sorted = date("Y-n-d", strtotime($date));
If you only need it to be presented that way and not actually changing the date stored, you can try using printf() as well
The one liner:
echo (DateTime::createFromFormat('j/n/Y','1/11/2020'))->format('Y/m/d');

PHP - Turn a timestamp (2012-07-12 20:26:00) Into two seperate variables that refelct the month and day values?

I would like to separately strip the day and month values out of this timestamp "2012-07-12 17:50:00".
So essentially I could have two variables like:
$month = 7
$day = 12
As I am not very proficient with php, specifically regex coding, I thought I would post this question to ask for advice as to how I would go about accomplishing something like this.
Any assistance, insight or input in this regard would be greatly appreciated. Thank you!
AS A NOTE: Futhermore, I would like to turn the two variables into an output like "12th July". This can be coded quite easily so I have not made this a part of the question but if there is a simple function that deals with this information would be much appreciated too!
As said in the comments, DateTime would be a good choice.
First, if your php config dosen't already set it up for you, set your default timezone by:
date_default_timezone_set('XXXX');
XXXX stand for a value out of the List of supported timezones
initialize your date by:
$DateTime = new DateTime();
depending on where you get the timestamp, lets assume you will create it out of PHP:
$timestamp = $DateTime->getTimestamp();
Now format the output
echo $month = $DateTime->format( 'm' );
echo $day = $DateTime->format( 'd' );
or to get you desired output:
echo $output = $DateTime->format( 'dS F' );
<?php
list($month,$day) = explode(':',date('n:j',strtotime('2012-07-12 17:50:00')),2);
echo 'Month: '.$month.'<br />'."\n";//Month: 7
echo 'Day: '.$day.'<br />'."\n";//Day: 12
?>
And...
<?php
echo date('jS F',strtotime('2012-07-12 17:50:00'));//Outputs: 12th July
?>
Assuming the timestamp is a string, something like this should work if you're looking for a regex solution...
<?php
$string = '2012-07-12 17:50:00';
preg_match_all('/\d{4}-(\d{2})-(\d{2})/', $string, $matches);
$month =$matches[1][0];
$day = $matches[2][0];
?>

change dd/mm/yy date format to yy/mm/dd using php

I'm having date 20/12/2001 in this formate . i need to convert in following format 2001/12/20 using php .
$var = explode('/',$date);
$var = array_reverse($var);
$final = implode('/',$var);
Your safest bet
<?php
$input = '20/12/2001';
list($day, $month, $year) = explode('/',$input);
$output= "$year/$month/$day";
echo $output."\n";
Add validation as needed/desired. You input date isn't a known valid date format, so strToTime won't work.
Alternately, you could use mktime to create a date once you had the day, month, and year, and then use date to format it.
If you're getting the date string from somewhere else (as opposed to generating it yourself) and need to reformat it:
$date = '20/12/2001';
preg_replace('!(\d+)/(\d+)/(\d+)!', '$3/$2/$1', $date);
If you need the date for other purposes and are running PHP >= 5.3.0:
$when = DateTime::createFromFormat('d/m/Y', $date);
$when->format('Y/m/d');
// $when can be used for all sorts of things
You will need to manually parse it.
Split/explode text on "/".
Check you have three elements.
Do other basic checks that you have day in [0], month in [1] and year in [2] (that mostly means checking they're numbers and int he correct range)
Put them together again.
$today = date("Y/m/d");
I believe that should work... Someone correct me if I am wrong.
You can use sscanf in order to parse and reorder the parts of the date:
$theDate = '20/12/2001';
$newDate = join(sscanf($theDate, '%3$2s/%2$2s/%1$4s'), '/');
assert($newDate == '2001/12/20');
Or, if you are using PHP 5.3, you can use the DateTime object to do the converting:
$theDate = '20/12/2001';
$date = DateTime::createFromFormat('d/m/Y', $theDate);
$newDate = $date->format('Y/m/d');
assert($newDate == '2001/12/20');
$date = Date::CreateFromFormat('20/12/2001', 'd/m/Y');
$newdate = $date->format('Y/m/d');

Reformat Custom Date in PHP

So I know how to format a date in PHP, but not from a custom format. I have a date that is a string "YYMMDD" and I want to make it "MMDDYYYY'. strtotime doesn't seem like it would do a good job of this when the MM and DD are both low digits.
Use str_split:
$date1 = "YYMMDD";
list($yy, $mm, $dd) = str_split($date1, 2);
// MMDDYYYY format, assuming they are all > 2000
$date2 = $mm . $dd . "20" . $yy;
If you're running PHP >= 5.3, have a look at DateTime::createFromFormat. Otherwise, if you don't want to use pure string manipulation techniques, use the more primitive strptime together with mktime to parse the time into a UNIX timestamp, which you can then format using date.
Maybe I am under-thinking this, but couldn't you just:
$oldDate='040220'; // February 20th, 2004
$year = substr($oldDate, 0,2);
$year += $year &lt 50 ? 2000 : 1900;
$date = preg_replace('/\d{2}(\d{2})(\d{2})/', '$1/$3/'.$year, $oldDate);
And you'd have the string you were looking for, or something close enough to it that you could modify from what I wrote here.
Have many dates prior to 1910? If not, you could check your YY for <=10, and if true, prepend "20" else prepend "19"... Kinda similar approach to MM and DD check for <10 and prepend a "0" if true... (This is all after exploding, or substring... Assign each part to its own variable, i.e. $M=$MM; $D=$DD; $Y=$YYYY; then concatenate/arrange in whatever order you want... Just another potential way to skin the proverbial cat...
Ended up doing:
$expiration_date_year = substr($matches['expiration_date'],0,2);
$expiration_date_month = substr($matches['expiration_date'],2,2);
$expiration_date_day = substr($matches['expiration_date'],4,2);
$expiration_date = date('m/d/Y', mktime(0,0,0,$expiration_date_month, $expiration_date_day, $expiration_date_year));

PHP mangles my dates

$doba = explode("/", $dob);
$date = date("Y-m-d", mktime(0,0,0, $doba[0], $doba[1], $doba[2]));
The above code turns any date i pass through into 1999-11-30 and i know it was working yesterday. Date is correct when I echo $doba. Anyone have any ideas?
Cheers
What is the format of $doba? Remember mktime's syntax goes hour, minute, second, month, day year which can be confusing.
Here's some examples:
$doba = explode('/', '1991/08/03');
echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[2], $doba[0]);
$doba = explode('/', '03/08/1991');
echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[0], $doba[2]);
or even easier: $date = date('Y-m-d', strtotime($dob))
It is a bit overkill to use mktime in this case. Assuming $dob is in the following format:
MM/DD/YYYY
you could just to the following to acheive the same result (assuming $dob is always valid):
$doba = explode("/", $dob);
$date = vsprintf('%3$04d-%1$02d-%2$02d', $doba);
If you have issues with what jcoby said above, the strptime() command gives you more control by allowing you to specify the format as well.

Categories