php date formatting not working - php

$t = DateTime::createFromFormat('Gi', '900');
$time_str = $t->format('gi a');
echo $time_str; //outputs 600 pm instead of 9am. Why? and How do I get 9am?
I am not sure where I am going wrong.. I am following what is given here in terms of date formatting:
http://php.net/manual/en/function.date.php
Thanks!

The documentation you linked is for the date() function. The DateTime::createFromFormat is not the same (though the format strings are pretty much identical).
I expect the format parsing is having trouble recognizing the difference between the hour and minute components.
If you split them up with a space, you get the desired result:
$t = DateTime::createFromFormat('G i', '9 00');
$time_str = $t->format('gi a');
echo $time_str;
// Output is 900 am
Edit:
The inability for PHP to parse a format string like Gi is a known bug. The parser for G doesn't know whether to read 9 or 90 and in the latter case that 90 is too high.

As i said in my comment this works :
$t = DateTime::createFromFormat('G i', '9 00');
$time_str = $t->format('gi a');
echo $time_str.PHP_EOL;
Cannot find any where written down - but suspect the time needs to be separated ... either by space or colon or something else

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

PHP mktime notice

I want to change given date and time or date only into Unix time.
I tried like this:
mktime("Jan-12-2012 2:12pm");
But it’s not working:
Even in PHP documentation I looked at many examples and many of them don’t consist the matter that I want.
And when I try:
$user_birthday=$_POST["user_birthday"];
$db_user_birthday=empty($user_birthday)?"":mktime($user_birthday);
$_POST["user_birthday"] was given value from form that is jan-12-2012 2:12pm
it show error like this:
Notice: A non well formed numeric value encountered in C:\Program
Files (x86)\Ampps\www\admin\index.php on line 76
How do I fix it or display time into Unix?
Use this one:
date("M-d-Y h:i:s", strtotime($user_birthday));
You should be using strtotime instead of mktime:
Parse about any English textual datetime description into a Unix
timestamp.
So your code would be this:
$user_birthday = $_POST["user_birthday"];
$db_user_birthday = empty($user_birthday) ? "" : strtotime($user_birthday);
Then you can process that date like this to get it formatted as you want it to:
echo date("M-d-Y h:ia", $db_user_birthday);
So your full code would be this:
$user_birthday = $_POST["user_birthday"];
$db_user_birthday = empty($user_birthday) ? "" : strtotime($user_birthday);
echo date("M-d-Y h:ia", $db_user_birthday);
Note I also added spaces to your code in key points. The code will work without the spaces, but for readability & formatting, you should always opt to use cleaner code like this.
You should take a look at this answer: convert date to unixtime php
Essentially, you have mixed up mktime() with strtotime(). strtotime() allows you to parse an English textual string into a Unix timestamp. mktime() constructs a unix datetime based on integer arguments.
For example (again taken from the question above)
echo mktime(23, 24, 0, 11, 3, 2009);
1257290640
echo strtotime("2009-11-03 11:24:00PM");
1257290640

strtotime not working

I am new to PHP and trying to convert a date from a registration form (in the form 01/01/2011) to Y-m-d so that it can be stored in the database.
This is the code I have, pretty sure it worked before but now it has stopped working. Any ideas?
$dateformat = $_POST['dob'];
$correctformat = date('Y-m-d',strtortime($dateformat));
I have checked what $_POST['dob'] is printing and it is correct, however the $correctformat is printing 1970-01-01 everytime.
Any help would be greatly appreciated.
Thanks
$currentformat = explode("/",$_POST['date']);
$newformat = $currentformat[2]."-".$currentformat[1]."-".$currentformat[0];
You could use DateTime::createFromFormat (note PHP 5 >= 5.3.0) instead of strtotime as strtotime acceptsm/d/Y not d/m/Y
try :
$dateformat = $_POST['dob'];
$correctformat = DateTime::createFromFormat('d/m/Y', $dateformat);
echo $correctformat->format('Y-m-d');
.1. Can you tell, looking at the date, if it have month or day first? If you can't - how it is supposed for the whatever program to determine the actual order?
.2. this operation require the very basic string manipulations anyone have to learn if planning to be a PHP user:
$chunks = explode("/",$_POST['date']);
$date = "$chunks[2]-$chunks[1]-$chunks[0]";
the order of chunks depends on the actual order of date parts
As Adam says, there is no strtortime() it should be strtotime()
Did you really test it with the literal string '01/01/2011'? Some of us were born before 1970 - which may be causing some confusion (strtotime() generates a 32 bit Unix time).
(beware that strtotime interprets xx/xx/xx[xx] using the americal style of mm/dd/yy[yy] rather than the european convention of dd/mm/yy[yy]).
It works for me with the typo removed:
[colinm#dev-sensor ~]$ php -q t.php
2011-01-01
[colinm#dev-sensor ~]$ cat t.php
<?php
print date('Y-m-d',strtotime('01/01/2011')) . "\n";

timestamp to date conversion problem in php

I have a timestamp like 1397105576 and I need to convert it to data format. I used:
echo $today = date('20y-m-d H:m:s',"1397105576");
I am getting:
Severity: Warning
Message: date() expects parameter 2 to be long, object given
in the codeigniter framework.
update:
i found the answer
the vaiable should be converted to long
ie
echo $today = date('20y-m-d H:m:s',intval("1397105576"));
echo date('Y-m-d H:m:s',"1397105576");
Returns
2014-04-10 14:04:56
Update:
That should work in codeigniter also...however there is a CI function that does something similar as above:
$datestring = "Year: %Y Month: %m Day: %d - %h:%i %a";
$time = time();
echo mdate($datestring, $time);
More about this can be found at the user guide. You might be interested in the unix_to_human() function in particular.
It seems everywhere except for Russell Dias made the mistake of using m as minutes and not i
Y-m-d H:i:s NOT "Y-m-d H:m:s"
your code is working correctly although try it again like this:
<?php
echo $today = date('Y-m-d H:m:s',1397105576);
?>
[edit]
I'm going to leave my answer here as a matter of pointing out/teaching you the non-CodeIgnitor sanitized version of PHP's object/typing (+date function!) system, but I HIGHLY suggest using, and accepting, Russell Dias' answer.
Is your example 100% literal?
Is your line of code literally echo $today = date('20y-m-d H:m:s',"1397105576"); or is it something more like echo $today = date('20y-m-d H:m:s',"$date");?
If it's the latter, and the variable is being created by a class, then it may not be properly-typed.
You could probably use… I think an int would suffice here, I think you could do something like echo $today = date('20y-m-d H:m:s',(int)$date);, again, assuming that your line of code is not in-fact literal.
I'm not 100% sure that int would work, if it doesn't, (float) is the only other numeric type that possible could. Perhaps (string)?
See Type Juggling.
As an aside, why are you using 20y? Please change that to a Y
From PHP's Date Docs:
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003
y | A two digit representation of a year | Examples: 99 or 03

Formatting String into MYSQL time

Ok, So i have a script that reads in a csv file and in there is a time that is formatted in the traditional HH:MM am/pm. I need to convert that into the mysql standard time format (HH:MM:SS).
This is what i have so far and it works
$schedule[$row]["TIME"] = date("H:i:s", strtotime($data[4]))
the problem is, if the input is formatted incorrectly there is no way i can tell. Is there some sort of "or die()" feature i can use or do i have to somehow check with a regex or something?
For example:
12:00 pm should be 12:00:00
but...if theres some issue with the format
12:d00 p.m comes out as 17:00:00
Thanks,
Ian
strtotime returns false if the parsing fails. So you can do:
$t = strtotime($data[4]);
if ($t === false)
//handle error
$schedule[$row]["TIME"] = date("H:i:s", $t);

Categories