I need to set variable, let's call it $times to specific amount of 8AM. I tried using mktime(08,00) but it returns
Parse error: Invalid numeric literal
Since I'm new to php, I still don't know which function is best used for thing such as this, weather it is time() date() or so.
My question is: how do I set $times to be 8AM of current day?
I've checked a lot of similar questions, but none of them have an answer. Not even the one that this is marked duplicate of.
Just remove the leading zeros.
mktime(8, 0);
It's because PHP is interpreting 08 as an octal number, and 8 is out of range in octal (0-7).
You can use date()
Dateformat reference: https://www.php.net/manual/en/datetime.format.php
$time = date("H:i") // 08:00
Related
I have checked out the following question/responses:
How do I get the format of “yyyy-MM-ddTHH:mm:ss.fffZ” in php?
The responses include links to Microsoft documentation to format dates but these do not work in PHP.
The the top answer suggest
date('Y-m-dTH:i:s.uZ') //for the current time
This outputs
2013-03-22EDT12:56:35.000000-1440016
Background
I am working with an API which requires a timestamp in the format above. The API is based in the UK (GMT) and my server is in Australia (AEST).
The example given in the API documentation ask for the date to be in this format:
2011-07-15T16:10:45.555Z
The closest I can get to this is date('c') which outputs:
2014-07-03T16:41:59+10:00//Notice the Z is replaced with a time diff in hours
I believe the 'Z' refers to a Zone but it is not mentioned in the PHP documentation.
Unfortunatly when I post this format, the API is reading the time and taking 10 hours off. I get an error saying that the date cannot be in the past (as it is checking against the local time in Melbourne, but seeing a time 10 hours earlier).
I have tried trimming the timestamp to remove the +1000 which the API accepts, but the record is showing as created as 10 hours earlier.
I need to match the timestamp required but I cannot find any way to replicate the above output, in PHP for Melbourne, Australia. Any assistance is much appreciated.
First question on SO so please let me know how I have gone
Z stands for the timezone UTC and is defined in ISO-8601, which is your desired output format, extended by the millisecond part.
Before outputting the time, you'll need to transfer local times to UTC:
$dt = new DateTime();
$dt->setTimeZone(new DateTimeZone('UTC'));
then you can use the following format string:
echo $d->format('Y-m-d\TH-i-s.\0\0\0\Z');
Note that I've zeroed the millisecond part and escaped the special characters T and Z in the format pattern.
The 3 number last before Z is just the 3 decimal place of time in milliseconds
The function microtime(true) gave the current time in milliseconds, would output like 1631882476.298437
In this situation it would be .298Z
Examples
1652030212.6311 = .631Z
1652030348.0262 = .026Z
1652030378.5458 = .545Z
Codes
$milliseconds = microtime(true);
// Round to integer
$timestamp = floor($milliseconds);
// Get number after dots
$uuuu = preg_replace("/\d+\./", "", "$milliseconds");
// Get last 3 number decimal place
$u = substr($uuuu, 0, 3);
// Print date by the timestamp timestamp
echo date("Y-m-d\TH:i:s", $timestamp). ".{$u}Z";
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
In order to get the date in the right format I want I used date("d-m-Y"). Now I want to get the time in addition to the date in the following format H:M:S How can I procede ?
Anytime you have a question about a particular function in PHP, the easiest way to get quick answers is by visiting php.net, which has great documentation on all of the language's capabilities.
Looking up a function is easy, just visit http://php.net/<function name> and it will forward you to the appropriate place. For the date function, we'll visit http://php.net/date.
We immediately learn a couple things about this function by examining its signature:
string date ( string $format [, int $timestamp = time() ] )
First, it returns a string. That's what the first string in the above code means. Secondly, the first parameter is expected to be a string containing the format. There is an optional second parameter for passing in your own timestamp (to construct strings from some time other than now).
date("d-m-Y") // produces something like 03-12-2012
In this code, d represents the day of the month (with a leading 0 is necessary). m represents the month, again with a leading zero if necessary. And Y represents the full 4-digit year. All of these are documented in the aforementioned link.
To satisfy your request of getting the hours, minutes, and seconds, we need to give a quick look at the documentation to see which characters represents those particular units of time. When we do that, we find the following:
h 12-hour format of an hour with leading zeros 01 through 12
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
With this in mind, we can no create a new format string:
date("d-m-Y h:i:s"); // produces something like 03-12-2012 03:29:13
Hope this is helpful, and I hope you find the documentation has benefiting to your development as I have to mine.
You can combine both in the same date function call
date("d-m-Y H:i:s");
You can have both formats as an argument to the function date():
date("d-m-Y H:i:s")
Check the manual for more info : http://php.net/manual/en/function.date.php
As pointed out by #ThomasVdBerge to display minutes you need the 'i' character
I'm doing a date search filter where I have my date displayed as "j.n.Y G:i (26.6.2012 15:22)".
A user can enter the whole date or only a portion of it: "26.6","6.2012","6","15:22" are all valid inputs. Because I need to check this date in the database the format needs to be changed to the one of the database. For that I use:
$datum = '25.6.2012';
$date = DateTime::createFromFormat('j.n.Y',$datum);
echo $date->format('Y-m-d H:i');
Where I get an error if $datum is not in the format j.n.Y (if I only enter j.n or one of the above mentioned string portions i get an error).
A problem is also, for the entered string 'j.n.Y', i get the right output of the date, which also has the current time added to the date string (which was not in the initial date string). Example: I enter "22.6.2012", then I get the output "2012-06-22 15:33".
Can these two problems get fixed with existing php functions or should I make my own?
Help would be greatly appreciated.
You can list your acceptable data formats in an array, and loop around DateTime::createFromFormat() to see if any of the inputs produce an acceptable date:
$formats = array( 'j.n', 'j.n.Y');
$datum = '25.6.2012'; $date = false;
foreach( $formats as $format) {
$date = DateTime::createFromFormat( $format, $datum);
if( !($date === false)) break;
}
if( $date === false) {
echo "Invalid date!\n";
}
Finally, if you want to get rid of the current time in the newly created object and set the time to 00:00:00, just use the setTime() method on the date object:
// Sets the time to O hours, 0 minutes, 0 seconds
$date->setTime( 0, 0, 0);
For the first problem, you will need to write some code of your own because some of your acceptable inputs are not among the recognized input formats. Normalizing the input value will require you to fully parse it (a regular expression is a good way to start), and then you can call DateTime::createFromFormat without trouble.
For the second problem, putting an exclamation mark ! at the beginning of your format string would fix the time issue. From the documentation:
If format contains the character !, then portions of the generated
time not provided in format, as well as values to the left-hand side
of the !, will be set to corresponding values from the Unix epoch.
The Unix epoch is 1970-01-01 00:00:00 UTC.
However, since you are going to need to fully parse the input as mentioned above the matter is moot. Also note that the exclamation mark would cause missing values for year, month and day to use defaults that are probably undesirable.
Hallo, I want to find the difference between today and another date,
convert todays date into unix time format here
<?php
echo '1st one'.strtotime(date("d.m.Y")).'<br>';
echo '2nd one'.strtotime(date("m.d.Y")).'<br>';
?>
The first echo is producing some value, but not the second one. What is the bug in it...please help..
strtotime makes assumptions based on the date format you give it. For instance
date("Y-m-d", strtotime(date("d.m.Y"))) //=> "2010-09-27"
date("Y-m-d", strtotime(date("m.d.Y"))) //=> "1969-12-31"
Note that when given an invalid date, strtotime defaults to the timestamp for 1969-12-31 19:00:00, so when you end up with an unexpected date in 1969, you know you're working with an invalid date.
Because strtotime is looking for day.month.year when you use . as the delimiter, so it sees "9.27.2010" as the 9th day of the 27th month, which obviously doesn't exist.
However, if you change it to use / as the delimiter:
date("Y-m-d", strtotime(date("d/m/Y"))) //=> "1969-12-31"
date("Y-m-d", strtotime(date("m/d/Y"))) //=> "2010-09-27"
In this case, strtotime expects dates in month/day/year format.
If you want to be safe, Y-m-d is generally a good format to use.
It's worth pointing out that strtotime() does accept words like "today" as valid input, so you don't need to put a call to date() in there if all you want is today's date. You could just use strtotime('today');.
Come to think of it, a simple call to time(); will get you the current time stamp too.
But to actually answer the question, you need to consider that d.m.Y and m.d.Y are ambiguous - if the day of the month is less than the 12th, it is impossible to tell which of those two date formats was intended. Therefore PHP only accepts one of them (I believe it uses m/d/Y if you have slashes, but for dots or dashes it assumes d-m-Y.
If you're using strtotime() internally for converting date formats, etc, there is almost certainly a better way to do it. But if you really need to do this, then use 'Y-m-d' format, because it's much more universally reliable.
On the other hand, if you're accepting date input from your users and assuming that strtotime() will deal with anything thrown at it, then sadly you're wrong; strtotime() has some quite big limitations, of which you've found one. But there are a number of others. If you plan to use strtotime() for this sort of thing then you need to do additional processing as well. There may also be better options such as using a front-end Javascript date control to make it easier for your users without having to rely on strtotime() to work out what they meant.
strtotime does not consider 09.27.2010 to be a valid date...
You could check it like this:
<?php
// will return false (as defined by the docs)
echo var_dump(strtotime("09.27.2010"));
?>
The function expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp. US time format is : MM DD YYYY
look here for the Information about which formats are valid http://www.php.net/manual/en/datetime.formats.php. But what do you mean with deference between 2 dates? You mean the Timespan between 2 dates?
echo (time() - strotime("- 2 days")) . " seconds difference";
Something like that?
strtotime would not take the d.m.y format. good way is Y-m-d