Having trouble to convert a string date to a date object - php

This is the current date I got in PHP from getLastLogin():
Apr 22 2016, 01:44:17 CEST
This is the code that I use to convert it:
$ymd = null;
$dateObject = DateTime::createFromFormat('M d Y, H:i:s T', $player->getLastLogin());
if($dateObject){ $ymd = $dateObject->format("m/d/Y"); }
echo $ymd;
There is no error but it never goes into the if statement and therefore it's still null when I try to echo it.
My function getLastLogin() is working as well, so I think it's narrowed down to the actual format.
Thanks for help!

Related

Inserting dates into an SQL database using PHP [duplicate]

Crashes on:
<?php
$date = "13-06-2015 23:45:52";
echo Datetime::createFromFormat('d-m-Y h:i:s', $date)->format('Y-m-d h:i:s');
?>
PHP Fatal error: Call to a member function format() on boolean
But with other dates works well:
<?php
$date = "10.06.2015 09:25:52";
echo Datetime::createFromFormat('d-m-Y h:i:s', $date)->format('Y-m-d h:i:s');
?>
Wrong format?
Neither example work as you have multiple errors:
You forgot your second parameter to Datetime::createFromFormat()
h:i:s should be H:i:s
Your date in the second example is separated by a . not a -
Fixes:
<?php
$date = "13-06-2015 23:45:52";
echo DateTime::createFromFormat('d-m-Y H:i:s', $date)->format('Y-m-d h:i:s');
$date = "10.06.2015 09:25:52";
echo DateTime::createFromFormat('d.m.Y H:i:s', $date)->format('Y-m-d h:i:s');
?>
In my case I was getting this error because I was using microtime(true) as input:
$now = DateTime::createFromFormat('U.u', microtime(true));
In the specific moments where microtime returns a float with only zeros as decimals, this error appeared.
So I had to verify if its decimals and add a decimal part:
$aux = microtime(true);
$decimais = $aux - floor($aux);
if($decimais<=10e-5) $aux += 0.1;
$now = DateTime::createFromFormat('U.u', $aux);
EDIT:
Due to floating point precision sometimes floor brings an incorret floor, so I had to use a more straight forward approach:
$aux = microtime(true);
$now = DateTime::createFromFormat('U.u', $aux);
if (is_bool($now)) $now = DateTime::createFromFormat('U.u', $aux += 0.001);
While others try to get this question answered with a specific use case, I think it's time to wrap it up with a general answer.
Fatal error: Uncaught Error: Call to a member function format() on bool in path/to/source/code/file.php
When this exception error is raised, it's because the format() function gets a bad date format string. So, try to check the parameter according to https://www.php.net/manual/en/datetime.createfromformat.php#format
In my case, I sent an empty value from the input field and get's error
solution:
if ($this->input->post('date_fo_return') != "") {
$date_fo_return = $this->input->post('date_fo_return');
$date_fo_return2 = DateTime::createFromFormat('d/m/Y', $date_fo_return);
$data['date_fo_return'] = $date_fo_return2->format("Y-m-d H:i:s");
}
John Conde's answer is correct. If we forget the mistakes, the error occurs because the supplied input doesn't mach the format string.
Example:
DateTime::createFromFormat('D M j h:i:s e Y','Fri Nov 4 12:59:59 UTC 2022');
will return a DateTime object while following will return false.
DateTime::createFromFormat('D M j h:i:s e Y','Fri Nov 4 13:00:01 UTC 2022');
The culprit is the letter 'h' of the format string 'D M j h:i:s e Y'. For 12 hour format, which 13:00:01 is, you have to use the upper case 'H'.
If you look at the documentation, you can see the difference.
h: 12-hour format of an hour with leading zeros
H: 24-hour format of an hour with leading zeros
Basically if you look at this function Datetime::createFromFormat, you will find that function has 2 possible return values, they are DateTime object and false.
That fatal error happened because you call function format on false value which is invalid.
So you should check for return value first, then continue the process appropriately. Not only for this case (datetime), but also for another functions that have multiple possible return values.

PHP date_format(): How to format date from string value

I have a bit of PHP code:
$exd = date_create('01 Dec, 2015');
$exd = date_format($exd, 'Y-m-d');
echo $exd;
Which is used for formatting the date. The expected output would be 2015-12-01 but it returns 2016-12-01. What am i missing?
Use createFromFormat method first, provide the input format:
$exd = DateTime::createFromFormat('d M, Y', '01 Dec, 2015');
// arguments (<format of the input>, <the input itself>)
$exd = date_format($exd, 'Y-m-d'); // then choose whatever format you like
echo $exd;
The date_create() function accepts only the parameter link, This function is also and alias function of DateTime::__construct()
check the function date_create_from_format() its also a alias function of DateTime::createFromFormat(). Refer link
$exd = date_create_from_format('j M, Y', '01 Dec, 2015');
//$exd = date_create('01 Dec, 2015');
$exd = date_format($exd, 'Y-m-d');
echo $exd;
It can be a date function call simply. Use stringtotime for exact/precise date/time value
date("Y-m-d",strtotime("01 Dec 2015"))
When you run this code the out put will show
2015-12-01
this is because of the comma in the string which terminates the date string in the compiler. If you specify exactly the timezone (like
$timezone = 'America/New_York) . parameter you can show precise time as well.
i got the solution of your bug
that is date_format(datae_variable,date_format);
<?php
$exd = date_create('01 Dec, 2015');
$exd1 = date_format($exd,"Y-m-d");//here you make mistake
echo $exd1;
?>

String Replace Date & Time

a line of my XML looks like this:
<observation_time_rfc822>Thu, 09 Oct 2014 22:59:16 +0200</observation_time_rfc822>
I grab it and give it out:
$ob_time= $xml->observation_time_rfc822;
echo $ob_time;
The output looks like this:
Thu, 09 Oct 2014 22:59:16 +0200
But what I need should look like this (yes, the funny '%3A' replaces ':')
2014-10-09+22%3A59%3A16
I think string replace can do this, please someone can help me to find out!
Thank you!
Edit: Use #Ghost's solution, it correctly handles the timezone offset.
First you need to reformat your date. You do this by parsing it with strtotime and formatting it with the date function. Those "funny %3A replaces" are actually URL-encoded characters:
$date = date('Y-m-d H:i:s', strtotime($ob_time));
$date = urlencode($date); // 2014-10-09+20%3A59%3A16
You could use DateTime class in this case, then use urlencode():
Example:
$ob_time = (string) $xml->observation_time_rfc822;
$date = DateTime::createFromFormat('D, d M Y H:i:s O', $ob_time);
$real_date = $date->format('Y-m-d H:i:s');
echo urlencode($real_date); // 2014-10-09+22%3A59%3A16

how to convert timestamp to date in codeigniter

I want to convert 1373892900000 to Monday 2013/07/15 8:55 AM in Codeigniter.
However, I keep receiving a totally different result by converting the timestamp using the function i have written, please note:I need to change the dates according to different timezones, that is why I want to write it this way:
public function time_convert($timestamp){
$this->load->helper('date');
date_default_timezone_set('UTC');
$daylight_saving = TRUE;
$timezone = "UM4"; //toronto or new york timezone
$time = gmt_to_local($timestamp, $timezone, $daylight_saving);
$final_time = standard_date('DATE_RFC822', $time);
return $final_time;
}
Result from the above function is: Sat, 08 Dec 06 01:40:00 +0000
And if I don't put date_default_timezone_set('UTC'); in the above function, I get this date instead Sat, 08 Dec 06 02:40:00 +0100. My codeigniter seems to default the timezone to Europe/Berlin.
Can anyone please help me correct any of the mistakes I might have made?
Why not just use PHP's date function?
public function time_convert($timestamp){
return date('l Y/m/d H:i', $timestamp);
}
For different timezones use a DateTime object:
public function time_convert($timestamp, $timezone = 'UTC'){
$datetime = new DateTime($timestamp, new DateTimeZone($timezone));
return $datetime->format('l Y/m/d H:i');
}
Think that should work. Note: I tihnk you need at least PHP version 5.20 for the TimeZone class.
<?php
$time_str=1373892900000;
echo gmdate("fill with your format", $time_str);
?>
your format = format your time in php, reading this page for details.
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.gmdate.php
Appears as though an invocation of standard_date with the DATE_ATOM format may sort you:
echo unix_to_human(time(), true, 'us'); # returns 2013-07-12 08:01:02 AM, for example
There are a whole host of other options for the format, enumerated on the linked page.
This how to covert timestamp to date very simple:
echo date('m/d/Y', 1299446702);
to convert timestamp to human readable format try this:
function unix_timestamp_to_human ($timestamp = "", $format = 'D d M Y - H:i:s')
{
if (empty($timestamp) || ! is_numeric($timestamp)) $timestamp = time();
return ($timestamp) ? date($format, $timestamp) : date($format, $timestamp);
}
$unix_time = "1251208071";
echo unix_timestamp_to_human($unix_time); //Return: Tue 25 Aug 2009 - 14:47:51
if you want to convert it to a format like this: 2008-07-17T09:24:17Z than use this method
<?php
$timestamp=1333699439;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
for details about date:
http://php.net/manual/en/function.date.php
Your timestamp is coming from javascript on the client, I would guess, because it appears to be in milliseconds. php timestamps are in seconds. So to get the answer you want, first divide by 1000.
Showing the full year would have made the issue more obvious, as you would have seen the year as 45,506.

Date conversion and updating mongodb document using PHP

Progress :
1. I retireved date from a collection.
Example format : Fri Oct 05 14:59:31 +0000 2012
2. I was able to change its format.
CODE USED :
$cur=$col->find(array(),array("created_at"=>1,"_id"=>0));
// created_at = contains Date value
$cur_all=$col->find();
while($doc=$cur_all->getNext())
{
$doc2=$cur->getNext();
$pieces = implode(" ", $doc2);
//converted the array to string with space delimiting
if($pieces!=NULL)
{
$date1 = date_create_from_format("D M d G:i:s +O Y", $pieces);
echo date_format ( $date1 , 'Y-m-d G:i:s' );
//This is the format i would like to update in mongodb..
$filter = array('_id'=>new MongoId($doc['_id']));
$update = array('$set'=>array('created_at'=> newMongoDate($date2)));
$col->update($filter,$update);
}
}
QUESTION :
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
P.S : I did a lot of research on Stackoverflow (And other places, as well.) but I could not come to any conclusions. That is why this question. Let me know if there are any clarifications
Hmm even though you have explained your background well your actual question:
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
Is a bit confusing.
MongoDB will always save the date in one format and one format only when using ISODate: http://en.wikipedia.org/wiki/ISO_8601 (otherwise known as MongoDate in PHP) and it is probably best to not mess with this status quo.
So I would recommend you use the format Y-m-d G:i:s only as display, i.e.:
$date1 = new MongoDate();
var_dump(date('Y-m-d G:i:s', $date1->sec));
And you use the original $date1 object to actually save to the database.
Of course this would change if you were to create a date in your specified format however here is a piece of code for an example:
$date1 = new MongoDate();
$date2 = new MongoDate(strtotime(date ( 'Y-m-d G:i:s', $date1->sec )));
var_dump(date('Y-m-d G:i:s', $date2->sec));
You can use the $date2 as the date to save into MongoDB formed from the specific format you want.
look at http://php.net/manual/en/class.mongodate.php
your code should create a date using a unix timestamp
$date2 = ('23rd April 2013');
$update = array('$set'=>array(
'created_at'=> new MongoDate(strtotime($date2))
));
http://www.php.net/manual/en/function.strtotime.php

Categories