I am developing a website that allow user to see their equipments and know how much days passed till the repair started.
But i am having trouble getting the DATABASE information about the date.
I registered a column DATE and i made it TIMESTAMP with CURRENT_TIMESTAMP so it can automaticly atribut the date that joined the system.
I am using a script to get today's date and i put it in a table so it can show the user:
<script>
var days = new Date();
document.getElementById("days").innerHTML = days.toISOString().substr(0, 10);
</script>
Then i called a function that gets all equipment info ( client name, DATE, Type, etc...):
include_once('DataAccess.php');
$da = new DataAccess();
$res = $da->getEquipmentInfo();
while($row = mysqli_fetch_object($res)){
echo " <td id='days'></td> "; }
How do i make to calculate the difference between the database columns DATE and today's date to know how much days passed?
Thank you.
Convert both dates into unix and then find the difference between them and depending on if you want days, weeks, minutes, ect. you will have to convert. I dont have enough information for on your code and all your javascript to do it for you but here is a php example.
<?php
$now = time();
$db_unix = strtotime($res->theMysqlTimestamp);
$datediff = $now - $db_unix;
echo floor($datediff/(60*60*24));
?>
This takes the date now, your timestamp from mysql gets the unix timestamps, subtracts them, and then calculates the days difference between them.
Related
I've done endless searching but cannot find a solution that works for me. I am storing records in a mysql database that logs the UTC time it was created (UTC_TIMESTAMP()). I need to present the data to the user (using JavaScript) in their local time. I've tried the following and it is not working:
JavaScript:
function localizeDateStr(dateToConvert,divId){
newDate = new Date(dateToConvert);
document.getElementById(divId).innerHTML = newDate.toString();
}
HTML:
<div id="<?php echo $divId ?>" class="td-short"></div>
<script type="text/javascript">window.onload = localizeDateStr('<?php echo $entryTime;?>','<?php echo $divId;?>');</script>
The UTC date that is stored in the db is the same date that is being displayed.I am not seeing a converted date. Any help would be appreciated. Please advise.
Parsing a string through the Date constructor (or through Date.parse) is very sensitive to the format of the input string. With the value you gave in comments '2019-03-20 17:43:53', most implementations will interpret this in terms of local time. However, the specification does not require conformance of that, as it only describes a very particular format. Anything else is implementation dependent.
Assuming your strings are consistently in this format, and you want it interpreted as UTC, your options are:
Adjust the string to include a T separator between date and time parts, and end with Z to indicate UTC.
var newDate = new Date(dateToConvert.replace(' ','T') + 'Z');
Parse the string yourself:
var parts = dateToConvert.split(/[-: ]/g).map((x) => parseInt(x));
parts[1]--; // Months are 0-11, so adjust
var newDate = new Date(Date.UTC(...parts));
Use a library like Luxon:
var dt = luxon.DateTime.fromFormat(dateToConvert,
'yyyy-MM-dd HH:mm:ss', { zone: 'UTC' });
var newDate = dt.toJSDate();
or Moment:
var newDate = moment.utc(dateToConvert).toDate();
Hello today I encountered an issue with time stamp conversions.. In my web form I'm using an bootstrap-datepicker where users can pick date and time. Afterwards I convert those values with moment.js to unix timestamp and pass it to PHP page. In the PHP page if the user is in different country the value is different and in the end in database is inserted wrong value.
So it's like the server timezone is Latvia/Riga GMT+2 and user from Georgia/Tbilisi has GTM+4. He's selecting start date 12.01.2017 15:00, Moment.js passes it to PHP page in the DB value of start date is inserted 12.01.2017 13:00.
Here is code from js
var start_date = $("#start_date").val();
var start_time = $("#start_time").val();
var start = moment.utc(start_date + ' ' + start_time, "DD.MM.YYYY HH:mm").tz("Europe/Riga");
afterwards var is passed via ajax to PHP script like start.unix()
In PHP it receives
$startDate = date('Y-m-d H:i:s', $_GET['start']);
And time is received by 2 hours earlier..
What can I do so the user selects time from anywhere on the world PHP inserts in DB as it selected correctly without timezone conversion.
You should never pass dates with timezones from client-to-server, always have the server be the boss in this case, otherwise you're inevitably going to have inconsistency issues in your database.
You either:
Always use UTC+0 dates.
Use keywords that represent a date (ie. yesterday, now, two days ago).
Using a keyword allows you to make the server decide which date do you want based on UTC+0 timezone.
TL;DR;
Always use UTC+0 datetimes and convert them server/client-side (it's your preference) depending on which timezone a user is on.
You can use following JS to get Client Timezone in JS:
var time_zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var start_date = $("#start_date").val();
var start_time = $("#start_time").val();
In PHP:
function getDateTime($start_date, $start_time, $time_zone) {
$dateTime = $start_date . ' ' . $start_time;
$date = new DateTime($dateTime, new DateTimeZone($time_zone));
$serverTimeZone = date_default_timezone_get();
$date->setTimezone(new DateTimeZone($serverTimeZone));
return $date->format('Y-m-d H:i:sP');
}
This might help you to sync timezone
I have a dynamic table that displays a list of records with their date and time. The date and time displays correctly, but when I move to a hosting server, I get a different date and time, which I know is based on its timezone. I have seen different tutorials showing how to format date and time in different timezone when it is echoed on a page, but when I try it with my binded data from my recordset, it doesn't work online.
This is my binded recordset data:
<?php echo $row_forum['Date']; ?>
Please explain to me: "How to format for Africa/Lagos?".
Ok lets assume your server is in London and you want to know the time as it was in Lagos when the timestamp was created.
You need to use the handy DateTime class. Manual here
<?php
// assume this is when the row was created on the server in london.
$date = new DateTime('2000-01-01 01:00:00', new DateTimeZone('Europe/london'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Now you want to print the time that it was in Lagos when the row was created.
$date->setTimezone(new DateTimeZone('Africa/Lagos'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
The output would be
2000-01-01 01:00:00+00:00
2000-01-01 02:00:00+01:00
One hour ahead i.e. 02:00:00
So all you have to do is
// this should pick up the default timezone from the server
$date = new DateTime($row_forum['Date']);
// adjust the timezone you want the output to be in
$date->setTimezone(new DateTimeZone('Africa/Lagos'));
// get the data and time in whatever format you want to show it as
echo 'It was ' . $date->format('H:i:s') . ' in Lagos';
It should not matter where your server is now, or gets moved to sometime later, you will always get the time in Lagos.
For your purpose you can use DateTime and DateTimeZone like this:
$dt = new DateTime($row_forum['Date'], new DateTimeZone('Africa/Lagos'));
echo $dt->format('Y-m-d H:i:s');
var h = new Date(timestamp*1000).getHours();
date('H', $timestamp)
when I try to convert timestamp from javascript, i got different value from php
how can I get the same value from PHP?
ex. 28800, java-> 19, php->00
You'll have to assign the time into a javascript variable.
In your Javascript:
var server_time = '<?php print date("Y-m-d"); ?>';
Yes and this was the exact situation I was facing all day along.
First the JS time stamps are in milliseconds and PHP are not.
I was sending JS timestamps to PHP and trying to convert that to PHP date and all was going wrong.
So this is what I have done to resolve the issue
$jts = 1392143400000 ; // timestamp received from JS via ajax
$ts = $jts/1000
$date = date("Y-m-d",$ts);
So the dates got matched.
Now problem 2
Server is in EST time zone and when any specific date is sent from my time zone say IST the above also does not work.
Thankfully my app requires user timezone to be stored in DB at the time of registration I solved this mismatch as
$dt = new DateTime();
$ts = 1392143400000/1000 ;
$dt->setTimezone(new DateTimeZone('Asia/Kolkata')); // Get the timezone from user id.
$dt->setTimestamp($ts);
$date = $dt->format('Y-m-d');
I got 3 numeric text fields which are days, hours and min. I have scripted in such a way that user can only type 2 digit for each field.
Can someone help me to combine this 3 fields into one integer (which is a UNIX time) so that I can save it in the database as a single column time.
HTML
<table><tr>
<td><input id='days' type='text' maxLength='2' placeholder='Days'></td>
<td><input id='hours' type='text' maxLength='2' placeholder='hours'></td>
<td><input id='min' type='text' maxLength='2' placeholder='Min'></td>
</tr></table>
JavaScript
var day = document.getElementById('days').value;
var hours = document.getElementById('hours').value;
var min = document.getElementById('min').value;
How do I combine this 3 variable (day,hours,min) into one single unix time variable and save it in the database. ( I know how to save it in the database but ? How do I combine the 3 variable and save it in a single JavaScript variable ? )
For this, I'm using you want to use the current month and year? You need to post the fields to your PHP script and use strtotime to formulate a timestamp:
$timestamp = strtotime(date('Y-M') . '-' . $_POST['days'] . ' ' . $_POST['hours'] . ':' . $_POST['min']);
Or, using JavaScript:
var d = new Date();
var ts = Math.round((new Date(d.getFullYear(), d.getMonth(), $('#day').val(), $('#hours').val(), $('#min').val())).getTime() / 1000);
Unix timestamps are the number of seconds since the beginning of the unix epoch.
The javascript Date object has a getTime method that returns the number of milliseconds since the beginning of the unix epoch.
So, if you want the value calculated on the client side:
var time = new Date(0,0,day,hours,min);
var milliseconds = time.getTime();
var seconds = milliseconds / 1000;
I'm not including an example of how to send a value to the server and save it to the database - that completely depends on the server-side technology you are using, and a quick google or stackoverflow search will help you with that part.