The dataset value is returning blank, no error on logfile.
$edate = trim($_POST['txtedate']); //user inputs date 12-01-2021
$int_effective_date = new DateTime(strtotime($edate));
echo "edate:- ".$edate."<br />";
echo "strtotime_edate:- ".strtotime($edate)."<br />";
echo "dateset:- ".strtotime($int_effective_date->format('Y/m/d'));
Result:
edate:- 2021-01-12
strtotime_edate:- 1610389800
dateset:-
To paraphrase #iainn: I'm not 100% sure why you're changing back and forth between DateTime objects and function calls to strtotime?
However, I can explain the most likely issue with your code...
strtotime
Firstly, let's clarify that 12-01-2021 is in the format (d-m-Y)? Hopefully it is, in which case PHPs strtotime function understands it correctly and produces a Unix timestamp (i.e. seconds passed since start of 1970)...
strtotime("12-01-2021");
// Output: 1610409600
// Notes:
// - Possible slight variations based on locale etc.
// - Lookup: date_default_timezone_set
// - This is with "UTC"
DateTime
You then pass that timestamp to DateTime but neglect to inform DateTime what kind of timestamp it is...
$int_effective_date = new DateTime(strtotime($edate));
// Is the same as...
$int_effective_date = new DateTime(1610409600);
However, DateTime doesn't see your timestamp as incorrect and tries to process it anyway...
In the format: HisYmd
But your input is too short for that so it only matches HisY
Time => 16:10
Year => 9600
Given the lack of data DateTime then fills in the blanks with today (example: 2021-02-05)
Day => 05
Month => 02
Which give you a complete timestamp of: 9600-02-05 16:10:40
strtotime from DateTime
Your next line of code then passes that timestamp back into a strtotime call...
echo "dateset:- ".strtotime($int_effective_date->format('Y/m/d'));
// Is the same as...
echo "dateset:- ".strtotime("9600/02/05");
Now, strtotime will always return something. Which means the first problem is that you're using echo which doesn't output (bool) false.
Try:
var_dump(strtotime("9600/02/05"));
You might ask, why doesn't that happen in the linked code example from #El_Vanja?
Answer
The answer to that, I believe, is that your PHP version is not up to date and anything over the 32 bit date range is going to return (bool) false from strtotime.
To fix this specific problem I suggest you update your PHP version (and OS if you haven't moved to 64 bit!)
However, further to that, I strongly suggest you stick to the DateTime object/class. It saves you from all of these annoying bugs if nothing else...
For reference:
echo strtotime( (new DateTime("#1610409600"))->format("Y-m-d") ); // Output: 1610409600
echo strtotime( (new DateTime("2021-01-12"))->format("Y-m-d") ); // Output: 1610409600
Related
I am saving the timestamp in SQL as bigint(20). The number is correct and in android or https://www.epochconverter.com it works fine.
However I am not able to create a date-string based on the timestamp received from database.
First of all, the timestamp seems to come from database as a String, so I can't just say echo date("d.m.Y, $timestamp). The result is the famous 31.12.1969.
So I tried echo date("d.m.Y, strtotime($timestamp)). However, even though strtotime is said to be able to convert almost everything to a timestamp, a simple String containing a timestamp is not possible. Results still remained on the last day of Brian Adams probably favorite year.
Some progress I made by casting the $timestamp to a float value like so: echo date("d.m.Y", floatval($timestamp));. However, now things got really confusing for me. I seemed to have successfully converted my timestamp, however, date() gave me the dates around 02.09.52299.
The timestamps I am using are timestamps of current time, e.g. 1588489252657, which currently leads to the date 23.03.52307.
So all I want is to come to a date based on the timestamp 1588489252657 to see the 03.05.2020 on my screen.
Thanks for any advice!
<?php
$timestamp = 1588489252657; // Timestamp in Milliseconds
$seconds = round($timestamp/1000, 0); // Timestamp Rounded to Seconds
$date = new DateTime(); // Create PHP DateTime Object
$date->setTimestamp($seconds); // Set the Timestamp
echo $date->format('Y-m-d H:i:s'); // Specify the Required Format
The answers are pretty much in the comment sections. But I have shared this answer since this is another approach in OOP fashion. You can leverage the power of PHP's DateTime Class.
PHP Official Documentation For DateTime Class Link Below:
PHP DateTime Class
You have to transform the timestamp to seconds first.
$timestamp = 1588489252657;
$dateInUnixSeconds = round($timestamp / 1000, 0);
$date = \DateTimeImmutable::createFromFormat('U', (string) $dateInUnixSeconds);
echo $date->format('d.m.Y');
PS:
I recommend you to use the \DateTimeImmutable object to avoid mutability problems.
https://github.com/Chemaclass/php-best-practices/blob/master/technical-skills/immutability.md
I've been struggling to get an exact answer for this question. There are many that are close to what I'm wanting but seem to still be just off. The application of this is to ensure that a booking can't be made for a past date.
I have a form which has an input for time & another for date. Firstly, I wan't to take both of these inputs & convert them to a timestamp.
This code returns nothing
$time_date = sprintf("%s %s", $pDate, $pTime);
$objDate = DateTime::createFromFormat('H:ia d/m/Y', $time_date);
$stamp = $objDate->getTimestamp();
echo $stamp;
So I've have tried using something like this
$pDate = $_POST['pDate'];
$pTime = $_POST['pTime'];
$full_date = $pDate . ' ' . $pTime;
$timestamp = strtotime($full_date);
echo $timestamp;
But for some reason it is returning an incorrect timestamp. (i've been using an online converter) 02/06/2014 as date & 12:23am as time, is not 1401625380. This according to the converter is Sun, 01 Jun 2014 12:23:00 GMT.
Does someone have working code for returning a timestamp of both time & date inputs?
Secondly I want to compare this timestamp with a specified one & check to see if it is greater than. I've created a timestamp for my timezone with this
$date = new DateTime(null, new DateTimeZone('Pacific/Auckland'));
$cDate = $date->getTimestamp();
echo $cDate;
and will simply have an if statement which compares the two and echos the appropriate message.
I feel as though there are multiple question on here that are ALMOST what I'm wanting to achieve but I can't manage to get them working. Apologies for the near duplicate.
Note: I'm using ajax to post form data (if this could possibly interfere).
Your second code snipped is correct. Assuming it's in datetime format (Y-m-d H:i:s).
From php manual about strtotime():
Each parameter of this function uses the default time zone unless a time zone is specified in that parameter.
Check your PHP default time zone with date_default_timezone_get() function.
To compare two dates, be sure they both are in same time zones.
For datetime inputs I personally use jQuery UI timepicker addon.
you receiving the time and date in string format - so i don't believe the ajax can interfere.
as for your question:
first of all - find out what is the locale timezone of your server. you can do it by this function: date_default_timezone_get.
if the answer doesn't suit you - you can use its "sister": date_default_timezone_set, and change it to whatever value you need (like 'Pacific/Auckland' - see the documentation there). it is also recommended to return it to the original value after you finish your stuff.
i believe fixing your locale timezone will solve your issue.
I am new to PHP and I am trying to learn more of php date and time but I seem to get stuck with this.
I have this date format:
ddMMyyHHmmss
And an example is 120813125055 but I am trying to manipulate the string such that it will give me the format of:
yyyy-MM-dd HH:mm:ss (in the example above, 2013-08-12 12:50:55)
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
But it always gives me a result of 1969-12-31 18:00:00.
I assume that I need to do some string manipulation in PHP for this but I was wondering if there is an easier and more efficient way to do it?
I think what you're looking for is in the second response answered here: how to re-format datetime string in php?
To summarize (and apply to your example), you could modify the code like this.
$datetime = "120813125055";
$d = DateTime::createFromFormat("dmyHis", $datetime);
echo $d->format("Y-m-d H:i:s");
Use date_create_from_format:
$ts = date_create_from_format('dmyHis', '120813125055');
$str = date('Y-m-d H:i:s', $ts);
strtotime() only works on EASILY recognizable formats. Your is a ugly mix of garbage, so no surprise that strtotime bails with a boolean FALSE for failure, which then gets typecast to an int 0 when you tried feed it back into date().
And of course, note that your time string is NOT y2k compliant. two digit years should never ever be used anymore, except for display purposes.
You're using your function call and the argument the wrong way around.
In your example, php will try to return you the date for which the time is 'strtotime('120813125055')', and this function returns false (interpreted as 0). So you get returned the date formatted in 'Y-m-d H:i:s' for the Unix epoch.
You will need to get the actual timestamp of your string, so use http://www.php.net/manual/en/datetime.createfromformat.php.
You are mistaken here..
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
You shouldn't use only numbers ( doesnt matter its an integer or a string ), than it will always give you the same thing.
You can use any other valid date and time ( E.G. 6 Jun 2013, 5 may 12...) . Because what strtotime() do is detect a valid date and convert it into timestamp.
cI use jQuery calendar date picker on my form. When the date is not filled, it always shows "1969-12-31" value. I did not want to show this value, 0000-00-00 is fine for me.
My MySQL date column is receive_dt DATE NOT NULL,
This is a snippet code from the PHP file to handle the form.
...
$rcv_dt = $_POST['receive_dt'];
list($year,$month,$day)=explode('/',$rcv_dt);
$timestamp=mktime(0,0,0,$year,$month,$day);
$receive_dt=date('Y-m-d',$timestamp);
..., receive_dt) VALUES (....,'$receive_dt')...
I've tried to do the strtotime() but no luck.
$receive_dt=date('Y-m-d', strtotime($rcv_dt));
I've even changed the MySQL reveive_dt column to DATE NULL, but still no luck.
Firstly, the fact that you're getting the end of 1969 rather than the beginning of 1970 (the "Unix epoch" begins at midnight on 1st Jan 1970) suggests you have some timezone-handling bug causing you to "lose" an hour, so just a heads-up on that.
Now, the reason you're seeing this at all, is that PHP's date formatting functions treat whatever input you give them as a number; if you give them an empty string, or null, this will be converted to the number 0, and interpreted as the beginning of the Unix epoch - 1st Jan 1970. MySQL will probably do something similar if you try to pass it an empty string or 0 when populating the column.
What you need to do is specifically detect this case - easy enough if your application should never actually have 1st Jan 1970 as input - and specifically insert a NULL into the database rather than formatting the date.
$invalid_dates='1969-12-31'; // anything before
$rcv_dt = $_POST['receive_dt'];
if(strtotime($invalid_dates) >= strtotime($rcv_dt))
{
$rcv_dt='0000-00-00'; // or $rcv_dt=date('Y-m-d'); // today
}
http://php.net/manual/en/function.checkdate.php
Learn to use the DateTime object. Using strtotime, mktime, and other integer based time formats is an outdated and bad approach.
$dt = date_create($_POST['receive_dt']);
if ($dt !== null)
{
echo $dt->format('Y-m-d H:i:s'); // insert this value
}
if you send $receive_dt as an empty string ..., receive_dt) VALUES (....,'')... (after checking the post variable is empty) then mysql will treat is as a null, otherwise php is sending a date of 0 which for mysql is the start date of the unix epoch.
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.