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
Related
I have frontend that accept date from calendar, with this format: 9/02/2021 11:00 AM
it then converted into these format: 2021-02-09 11:00, then it converted by this line of code:
var timeStamp = new Date('2021-02-09 11:00').getTime() / 1000;
I know these produce time in this value: 1612843200
Now in backend, i want to read that time value, and want to convert it back into Y-m-d H:i format, i tried date('Y-m-d H:i', '1612843200') but the result is 2021-02-09 04:00
my purpose is to get the time back to date format, and set timezone to UTC later, but i stumble in the first part before set timezone to UTC
how can i get the date back again?
You can use Intl.DateTimeFormat to get the timezone of the user.
See the below code to get user timezone.
let userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(userTimeZone);
Then you can send the user timezone, along with the seconds that you are using to your backend server.
There you can set the date_default_timezone_set using the timezone you are getting from the frontend.
See a list of timezone here.
Based on your need you can change the date-time accordingly at the backend.
In your PHP, you can try something like this
$userTimezone = $_POST["userTimeZone"];
$userSeconds = $_POST["seconds"];
date_default_timezone_set('UTC');
//Set this to get UTC timezone
You can use the following code,
date('j/m/d H:i A', '1612843200')
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();
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.
I am having one website in which it has functionality to Login with specific timezone regardless what's the timezone on client side.
Now,
In website when user selects a date in dialog.I am sending it to server side using JSON.stringify with several other properties.
But whenever it is received at server side date is changed.
Example :-
I logged in using (+05 : 30) India time zone "01/08/2015 00:00:00" and server is having Casablanca Timezone.
When the date is received at server side the date is reduced by One "31/08/2015".
I think it is because of timezone conversion.
I already checked following link :-
JSON Stringify changes time of date because of UTC
I already tried that answer :- https://stackoverflow.com/a/1486612/2592727
But i am unable to understand how that formula works. So it's better to get more details and work with some specific solution.
Requirement :-
I am allowing user to select only date.
I want same date to be received over server side.
How can i accomplish this? Please describe with more details if possible.
Is there any simple way to avoid this collision?
The JSON.stringify method stored the date as UTC in the string, and when you parse that in .NET you will get a DateTime that contains the exact same point in time, but converted to the local time of the server.
You can handle this in two ways, you can either convert the time back to the original time zone, or you can avoid using the Date data type.
Converting to the original time zone of course requires you to know what the time zone is. Example:
var zone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime userTime = TimeZoneInfo.ConvertTimeFromUtc(date.ToUniversalTime(), zone);
To avoid using the Date type, you would format the date into a string before serialising it. Example:
var s = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
On the server side you would parse the string using the same format:
DateTime userTime = DateTime.ParseExact(date, "yyyy-M-d", CultureInfo.InvariantCulture);
Use the format yyyy-mm-dd hh:mm:ss and you will never get this ever again, regardless of timezone
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');