How to convert ISO8601 to Date format in php - php

How to convert this (in ISO8601 format): 2014-03-13T09:05:50.240Z
To this (in MySQL DATE format): 2014-03-13
in php?

try this
$date = '2014-03-13T09:05:50.240Z';
$fixed = date('Y-m-d', strtotime($date));
The complete date function documentation can be found here: http://php.net/manual/en/function.date.php
The PHP function "strtotime" does nothing else then converting your timestring into an unix timestamp.
Hope I could help :)
P.s.:
Just in case strtotime will return 0 try using this:
$date = '2014-03-13T09:05:50.240Z';
$fixed = date('Y-m-d', strtotime(substr($date,0,10)));

Since PHP 5.2.0 you can do it using OOP and DateTime() as well (of course if you prefer OOP):
$now = new DateTime("2014-03-13T09:05:50.240Z");
echo $now->format('Y-m-d'); // MySQL datetime format

There is no reason to use the inefficient time functions. The most efficient way is to simply extract the first 10 characters:
substr($date,0,10)
People, that are really coding for year ≥10000, can use:
substr($date,0,strpos($date,"T"))

Simply convert datetime description into a Unix timestamp using with strtotime and then five format using Date Formats
Try it will surely work for you.
$date = '2014-03-13T09:05:50.240Z';
$fixed = date('Y-m-d', strtotime($date));

For those using Carbon (php library), the parse() works quite well:
Carbon::parse($date)
https://carbon.nesbot.com/docs/

Today I have published an interitty/utils package that deals with, among other things, the ISO-8601 format and perhaps all permutations of this standard.
I hope it will help you too.
$dateTimeFactory = new Interitty\Utils\DateTimeFactory();
$dateTime = $dateTimeFactory->createFromIso8601('1989-12-17T12:00:00Z');

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

PHP strtotime() function that accepts a format?

strtotime() in PHP works great if you can provide it with a date format it understands and can convert, but for example you give it a UK date it fails to give the correct unix timestamp.
Is there any PHP function, official or unofficial, that can accept a format variable that tells the function in which format the date and time is being passed?
The closest I have come to doing this is a mixture of date_parse_from_format() and mktime()
// Example usage of the function I'm after
//Like the date() function but in reverse
$timestamp = strtotimeformat("03/05/2011 16:33:00", "d/m/Y H:i:s");
If you have PHP 5.3:
$date = DateTime::createFromFormat('d/m/Y H:i:s', '03/05/2011 16:33:00');
echo $date->getTimestamp();
You are looking for strptime, I think. you can use it to parse the date and then use mktime if you need a UNIX timestamp.
function strotimeformat($date, $format) {
$d = strptime($date, $format);
return mktime($d['tm_hour'], $d['tm_min'], $d['tm_sec'],
$d['tm_mon'], $d['tm_mday'], $d['tm_year']);
}
This will work with PHP 5.1 and onwards.
strtotime assumes it's a US date/time when using / as the separator. To get it to think it's a Euro date/time, use - or . as the date separator. You can change the /s to -s or .s with a simple str_replace()

add one year to datetime with php

$data['user']['time'] = '2011-03-07 00:33:45';
how can we add 1 year to this date ?
something like $newdata = $data['user']['time'] + 1 year ?
or
$newdata = 2012-03-07 00:33:45
Thanks
Adam Ramadhan
strtotime() is the function you're looking for:
$data['user']['seal_data'] = date('Y-m-d H:i:s', strtotime('+1 year', strtotime($data['user']['time'])));
First, you have to convert the MySQL datetime to something that PHP can understand. There are two ways of doing this...
Use UNIX_TIMESTAMP() in your query to tell MySQL to return a UNIX timestamp of the datetime column.
SELECT whatever, UNIX_TIMESTAMP(myTime) AS 'myUnixTime' FROM myTable;
Use DateTime::createFromFormat to convert your string time to something PHP can understand.
$date = DateTime::createFromFormat('Y-m-d H:i:s', $data['user']['time']);
Once that is done, you can work with the time... Depending on the method you used above, you can use one of the following.
If you have a unix timestamp, you can use the following to add a year:
$inAYear = strtotime('+1 year', $data['user']['unixTime']);
If you have a DateTime object, you can use the following:
$inAYear = $date->add(new DateInterval('P1Y'));
Now, to display your date in a format that is respectable, you must tell PHP to return a string in the proper format.
If you have a unix timestamp, you can use the following:
$strTime = date('Y-m-d H:i:s', $inAYear);
If you have a DateTime object, you can use the following:
$strTime = $inAYear->format('Y-m-d H:i:s');
Alternatively, if you don't want to deal with all of that, you can simply add one year when you query.
SELECT whatever, DATE_ADD(myTime, INTERVAL 1 YEAR) AS 'inAYear' FROM myTable;
Current (2017) Practice is to use DateTime
This question is top on a google search for "php datetime add one year", but severely outdated. While most of the previous answers will work fine for most cases, the established standard is to use DateTime objects for this instead, primarily due strtotime requiring careful manipulation of timezones and DST.
TL;DR
Convert to DateTime: $date = new DateTime('2011-03-07 00:33:45', [user TZ]);
Use DateTime::modify: $date->modify('+1 year');
Format to needs.
Change the timezone with DateTime::setTimezone from the list of supported timezones: $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
Convert to string with DateTime::format: echo $date->format('Y-m-d H:i:s');
Following this pattern for manipulating dates and times will handle the worst oddities of timezone/DST/leap-time for you.
Just remember two final notes:
Life is easier with your system timezone set at UTC.
NEVER modify the system timezone outside of configuration files.
I've seen too much code that relies on date_default_timezone_set. If you're doing this, stop. Save the timezone in a variable, and pass it around your application instead, please.
More Reading
How to calculate the difference between two dates using PHP?
Convert date format yyyy-mm-dd => dd-mm-yyyy
PHP - strtotime, specify timezone
I think you could use strtotime() to do this pretty easily. Something like:
$newdata = date('c', strtotime($data['user']['time'] . ' +1 year'));
Though the 'c' format string isn't the same as your input format. You could consult date()'s docs for how to construct the correct one.
'Y-m-d H:i:s' — as Tim Cooper suggests — looks correct.
This should do the trick (not tested).
$data = "2011-03-07 00:33:45";
echo 'Original date +1 year: ' . date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s", strtotime($data)) . " +1 year"));
First-of-all if your date format is separated by a slash (/), like '2019/12/31' then you should convert it in dash (-) format, like '2019-12-31', to do so use str_replace() function.
$string = str_replace('/', '-', '2019/12/31'); //output: 2019-12-31
To add time/day/month/year do not use strtotime() function, because it can't add a time which is beyond year 2038.
So here I would prefer to use DateTime() function.
$string = '2000-01-01';
$date = new DateTime($string);
$date->add(new DateInterval('P60Y5M2DT6H3M25S')); //60 Years 5 Months 2 Days 6 Hours 3 Minutes 25 Seconds
echo $date->format('Y-m-d H:i:s'); //output: 2060-06-03 06:03:25

PHP Convert ISO date to more readable format?

Just a simple question. How do I convert a PHP ISO time (like 2010-06-23T20:47:48-04:00) to something more readable? Is there a function already built in PHP? I've looked around but I haven't seen anything to convert times. If there's not a function, is it possible?
Thank you
$format = "d M Y"; //or something else that date() accepts as a format
date_format(date_create($time), $format);
Try this:
echo date( "Y-m-d H:i:s", strtotime("2010-06-23T20:47:48-04:00") );
Format this part "Y-m-d H:i:s" using format from this documentation http://php.net/manual/en/function.date.php
echo strftime("%b %e %Y at %l:%M %p", strtotime($ios));
will do
strptime() converts a string containing a time/date with the format passed as second argument to the function. The return value is an array containing values for day, month, year, hour, minutes, and seconds; you can use those values to obtain a string representing the date in the format you like.
strptime() is available since PHP 5.1.0, while the class DateTime is available since PHP 5.2.0.
I think you should try strftime
http://php.net/function.strftime
Sounds like you're looking for the date function: http://php.net/function.date
Possibly paired with the strtotime function: http://php.net/function.strtotime
For a short date try this:
$a_date = '2010-06-23T20:47:48-04:00';
echo date('Y-m-d', strtotime($a_date));

PHP converting date format

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;
}
}

Categories