timestamp from both date & time inputs and compare php - php

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.

Related

STRTOTIME in php returning blank value

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

Convert timestamp coming from SQL database to String

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

Timestamp Difference and Output

In My SQL Database I have a Timestamp Column with values like this one representing the Date of the last edit:
2015-01-17 08:55:34.000000
I want to compare the Date with the current date and when is the same day I want to echo Today and otherwise I want to Display the Date of the last edit:
$timefromdb = '2015-01-17 08:55:34.000000'
$edit = strtotime($timefromdb);
if($edit > $_SERVER['REQUEST_TIME']){echo "Today";}
else{
echo strftime("on %A, the %d %B %Y", $edit);
}
echo " at ".date('h:i',$edit)
It always Displays 01/01/1970. There must be a Problem with strtotime. I did a bit of research and it seems like my Timestamp Format isn't a valid one: http://php.net/manual/en/datetime.formats.php
Around the web are a lot of Questions about converting Timestamps but I just can't find the right one: I also got a bit confused by all the functions to convert date stuff.
So can someone Tell me how to get a valid Timestamp for using it in strftime and to compare it to the REQUEST_TIME.
Thanks in Advance!
UPDATE: As Always: The Problem sits in Front of the PC. I declared the Variable but never assgined the Timestamp to it :)
Chop off the .000000 from the date as it makes the date a format strtotime() cannot work with. There's several ways to do this. A simple substr is one of them.
$timefromdb = substr('2015-01-17 08:55:34.000000', 0, -7);
I'm not exactly understood you, but
try
1. compare gettype( $edit ) and gettype($_SERVER['REQUEST_TIME'])
2. not sure what $timefromdb will be more then $_SERVER['REQUEST_TIME'], because IMHO when user edited data, time of it action will me less then current time.

Timezone is correct but Time is not - PHP MySQL

I'm making a little twitter clone just for learning and I came across a problem where, before and after allowing users to select the timezone they are in, the time displaying when they would tweet a certain thing was wrong.
Here are snippets of my code:
/* current date/time whenever they send a tweet */
$time = date('Y-m-d H:i:s');
/* Insert into db as `time` */
/* Time retrieved as $value['time'] & users timezone as $_SESSION['timezone'] */
/* Convert to users timezone */
$users_timezone = new DateTimeZone($_SESSION['timezone']);
$date = new DateTime($value['time']);
$date->setTimeZone($users_timezone);
$new_date = $date->format('M j, o g:i a e');
echo $new_date;
It is currently 11:32am here in the LA area, yet after conversion it shows 6:26pm
My default is in Berlin, which it is currently 8:33pm but before conversion it shows 1am
Can anyone give me any insight into this? First time doing this.
Check System Time
Please check your current system time of your server by running date via ssh.
I believe php gets the date from the system therefore if your system time is incorrect then your php time would also be incorrect.
Check $value['time']
You are using the construct method within the DataTime class. Here is the documentation for that method.
http://www.php.net/manual/en/datetime.construct.php
Make sure $value['time'] is in an acceptable format. On way to do this easily is to use the strtotime function. This will make a unix timestamp from $value['time'] and that will probably satisfy the construct method of the DateTime class.

How to insert a proper date into a mysql query

I was using this query to fill my values:
mysql_query("INSERT INTO 'drivers'(coupon,loyalty,etairia,package,pump,date,merchant,public,private,
amount,plate,nonce)VALUES('".$_REQUEST['coupon']."','".$_REQUEST['loyalty']
."','".$_REQUEST['etairia']."','".$_REQUEST['package']."',0,NOW(),'".$_REQUEST['m']."
','".$_REQUEST['pu']."','".$_REQUEST['pr']."','".$_REQUEST['amount']."',
'".$_REQUEST['plate']."','".$_REQUEST['nonce']."');");
This is working fine, but with NOW() I have the server hour so I want to convert it to my local hour.
I found this on another question:
$date = new DateTime();
$date->setTimezone(new DateTimeZone('Europe/Athens'));
$fdate = $date->format('Y-m-d H:i:s');
I printed it and it returned the correct hour.
Finally I tried to put it inside the query instead of NOW() but when I run it it doesn't even make a row to my base.
This is my code now:
mysql_query("INSERT INTO `drivers`.`pay`(coupon,loyalty,etairia,package,pump,date,merchant,public,
private,amount,plate,nonce)VALUES('".$_REQUEST['coupon']."','"
.$_REQUEST['loyalty']."','".$_REQUEST['etairia']."','".$_REQUEST['package']
."',0,'".$fdate."','".$_REQUEST['m']."','".$_REQUEST['pu']."',
'".$_REQUEST['pr']."','".$_REQUEST['amount']."','".$_REQUEST['plate']."','"
.$_REQUEST['nonce']."');");
My php version is 5.5.9
To get local time:
echo date("Y-m-d H:i:s");
To get global time:
echo gmdate("Y-m-d H:i:s");
Or set your timezone something like this:
date_default_timezone_set('Europe/Athens');
print date('Y-m-d H:i:s')."\n";
I will suggest you, do not use mysql_.It is deprecated from the latest version of PHP.Use mysqli_ instead of this.
As has already been suggested, try using "date_default_timezone_set" and "date" to get the date in your local timezone.
I would also recommend a couple of other things:
Use mysqli instead of mysql functions as mysql functions are deprecated
Escape your strings! To avoid SQL injection use mysqli_real_escape_string on anything that comes from the request
I understand that your question is "what is wrong with this mysql query ?". The problem is that you don't see which error is produced by MySQL.
This case is known for PHP as a "WSOD" or White screen of death : nothing is displayed, generally because of some error setting (php function error_reporting).
If you take a look at this page, you will find a way to declare a error handler, which is a great time saver when programming PHP. You will also read the reason of your error and you then can explain it to us all. :-)
Check out UNiX_TIME stamp. It will store as a big int . It's basically seconds count from a particular date which the clock was set . It's a good way as it gives you flexibility in retrieving in any format you want. You can convert it in client side. Hope this helps
You can use date('Y-m-d H:i:s') or gmdate('Y-m-d H:i:s') to get the current date and time. You will need to make sure that your date column is set as a DATETIME type
I don't know if you still need it, but with the following code
$timezone = +1;
$date = gmdate("Y-m-j H:i:s", time() + 3600*($timezone+date("I")));
You can change the timezone as you want (for example my timezone is GMT + 1 where I am now) and with the date you also no need to worry about when daylight time changes.
For you is
$timezone = +2;

Categories