javascript convert timestamp different from PHP - javascript

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

Related

How to format datetime stamp with Javascript and PHP

The main issue: I gather the initial parameter in the datetime format, and use php date function to convert it to a readable format. From this format, I need to convert the date back to the same datetime parameter using javascript.
I have tried the getTime() function in javascript to get a datetime parameter conversion.
<?php
$_REQUEST['date'] = 1500786000;
$date=date('Y-m-d', $_REQUEST['date']);
echo "<span id='date'>$date</span>";
?>
<script>
var pdate=new Date('#date').val().replace(/-/,'\/'));
console.log(pdate.getTime());
</script>
The original datetime parameter starts as 1500786000, is formatted as 2017-02-23 via PHP.
The javascript conversion is 1500786000000, three 0s off from the expected format.
I would prefer not to use an alternative library, so anything that can be used in native javascript would be most helpful.
If you follow the same steps this is as expected. You just need to divide the value by 1000 to get the value you are expecting.
The original datetime parameter starts as 1500786000 because it's in seconds.
In JavaScript it will return the number of milliseconds since 1970/01/01.
var seconds = new Date().getTime() / 1000; // if you want it to be seconds
Why don't you set both values in that span and use that as below:
<?php
$_REQUEST['date']=1500786000;
$date=date('Y-m-d', $_REQUEST['date']);
echo "<span id='date' data-date='".$_REQUEST['date']."'>$date</span>";
?>
<script>
var visibleDate= $('#date').val(); //You actual visible date
var rawDate= $('#date').data('date'); //You raw date
</script>
You don't need to make conversion in JS again. Hope it helps you.

Issue with date and time is conversation depending on local timezone

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

Difference Between Database Date and Today's Date

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.

Correctly format times between client (javascript) and the server (PHP)

I have a date object in javascript that goes as follows:
var date = 2014-12-01T00:00:00.000Z
And if I do:
var date = new Date(date);
date.setUTCMonth(date.getUTCMonth()+1);
Then the toISOString() method shows the expected value:
2015-01-01T00:00:00.000Z
But when I send that date time string through a POST to a PHP script and parse it back to a date using the DateTime class, I get this:
2014-12-31 19:00:00 -0500
I have tried setting the timezone using the DateTimeZone class and setting the timezone to my own and UTC without luck:
new DateTime($_POST['DateTime'],new DateTimeZone('America/Mexico_City'));
new DateTime($_POST['DateTime'],new DateTimeZone('UTC'));
Is there a way to set the timezone in javascript, using the Date class? Is there another way to work around this? I have small if not zero experience at all dealing with timezones.
Update:
Here's my ISO-formatted time string as per the toISOString() method (javascript):
2014-09-01T00:00:00.000Z
And here are the contents of my $_POST var as per print_r():
Array (
[DateTime] => 2014-09-01T00:00:00.000Z
)
Here's the output of my formatter function, using the '%c' format (es_MX locale):
dom 31 ago 2014 19:00:00 CDT
And the mentioned formatter function:
function formatDate($date) {
return utf8_encode(strftime('%c', $date->getTimestamp()));
}
I think when you send the date-string, it's somehow in different format. At least when I tested this, it works as expected:
$a = new DateTime('2015-01-01T00:00:00.000Z');
echo $a->format('Y-m-d H:i:s'); // Outputs '2015-01-01 00:00:00'
Demo here.
The issue you are getting is that when you use the following format
$date = '2015-01-01T00:00:00.000Z';
You are specifying a timezone.
Notice the "Z" at the end of your date, using it is the equivalent of "nautical timezone (GMT)"
Therefore when you try to run this code, you will get the exact same date which is not what you expect even when you have specified the DateTimeZone as a constructor parameter.
$dateTime = new DateTime($date, new DateTimeZone('America/Mexico_City'));
echo $dateTime->format('c'). "\n"; // 2015-01-01T00:00:00+00:00
$dateTime = new DateTime($date, new DateTimeZone('UTC'));
echo $dateTime->format('c'). "\n"; //2015-01-01T00:00:00+00:00
This is expected PHP behavior and is documented in the DateTime::__construct documentation under the $timezone parameter:
Note:
The $timezone parameter and the current timezone are ignored when the
$time parameter either is a UNIX timestamp (e.g. #946684800) or
specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
In your case you are specifying a timezone directly with in your date (the "Z") and this is why the DateTimeZone object is ignored.
To avoid this and set a custom time zone either set it in the date time string or get rid of the Z.:
$date = '2015-01-01T00:00:00.000';
$dateTime = new DateTime($date, new DateTimeZone('America/Mexico_City'));
echo $dateTime->format('c'). "\n"; // 2015-01-01T00:00:00-06:00
$dateTime = new DateTime($date, new DateTimeZone('UTC'));
echo $dateTime->format('c'). "\n"; // 2015-01-01T00:00:00+00:00
$date = '2015-01-01T00:00:00.000 America/Mexico_City';
$dateTime = new DateTime($date);
echo $dateTime->format('c'). "\n"; //2015-01-01T00:00:00-06:00
See the code working for different versions of PHP here: Demo
Also take a look at this related question I asked recently: PHP DateTime Timezones - Constructor vs Setter method

How to format time and date from a recordset?

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

Categories

Resources