Compare Javascript date with php current date - javascript

I am using the function :
var date = new Date();
in javascript. it gives the following output
"Sat May 13 2017 22:19:25 GMT+0500 (Pakistan Standard Time)"
Now I will embed this date in a URL and on server side , I will receive this date. On server i have a php script , now in this script i want to compare the date received from javascript client side with current php time and check if the difference between date time zone sent from javascript client side and current php date time zone is greater than 5 minutes or not .

You should use timestamp comparison.
JS:
var timestamp = (new Date()).getTime(); // send this to your php
PHP:
$timestampFromJs = intval($_GET["ts"]); // just made it up
$ts = time() * 1000; // js timestamp is milliseconds
if($ts - $timestampFromJs > 5000*60) ...
UPDATE: If you need timezone safe comparison:
JS:
var timestamp = (new Date()).getTime();
PHP:
$timestampFromJs = intval($_GET["ts"]); // just made it up
$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));
$ts = $date_utc->getTimestamp() * 1000; // js timestamp is milliseconds
if($ts - $timestampFromJs > 5000*60) ...

Related

How to convert user input datetime into UTC and store in database with remote server in Javascript

I have a datetime which is from user input. And need to store into database.
The output of date in console.log() in remote server is different from local server.
Data from user input:
ui_date = '2018-05-23';
ui_time = '10:00'; // literally meant for 10 oclock
//.... i manage to concatinate ui_date and ui_time and convert to ISO datetime
Now...
Output from local server
console.log(myDate.toISOString());
// outputs: 2018-05-23T02:00:00.000Z
// This is correct UTC since I'm in philippines and the offset is +8
// Localserver automatically convert it to UTC
Output from remote server
console.log(myDate.toISOString());
// outputs: 2018-05-23T10:00:00.000Z
// This is wrong because it is in local time not UTC
It seems remote server cannot convert this datetime into UTC.
Does anyone have an idea about this?
UPDATE
showing the actual code:
By the way I'm using node.js as a server.
Input from user:
{
"date": "2018-05-23",
"time": "10:00"
}
my route:
router.post('/test_datetime', function(req, res, next) {
console.log(req.body.date);
console.log(req.body.time);
var date = req.body.date;
// get the date, month and year
var dd = new Date(date).getDate();
var mm = new Date(date).getMonth();
var yy = new Date(date).getFullYear();
// get the hour and min from "10:00" and convert to number
var hour = parseInt(req.body.time.substr(0, 2));
var min = parseInt(req.body.time.substr(3, 4));
// constructed datetime
var datetime = new Date(yy, mm, dd, hour, min).toISOString();
console.log(datetime);
});
local server output of datetime:
2018-05-23T02:00:00.000Z
Remote server output of datetime:
2018-05-23T10:00:00.000Z
The problem is your construction of the JavaScript Date because the method you use doesn't take in to account the client's offset to UTC.
Creating a new date from the date string, as your code does initially, will assume the date (and time) is local.
Then just setting the hours and minutes on that date will keep everything in sync.
let date = '2018-05-23';
let time = '10:00';
// parse the date and time using the local timezone info
let d = new Date(date + ' ' + time);
// Generate the UTC ISO string
let isoDateTime = d.toISOString();
console.log(isoDateTime);

Send data in server timezone issue

I've spent a lot of time trying to understand the timezones. But i'm still confused.
Design:
1) Server in a different time zone than client.
2) I got the following Info in API call:
/api/config/v1/system/time
{
"timeZoneOffset": -18000000, (milli sec)
"serverTimeUTC": 1485332569157,
"serverTime": "Wed Jan 25 03:22:49 EST 2017",
"timeZone": "Eastern Standard Time"
}
3) I have no access on the server. (Can't really change any code there!)
4) I have a complete access on client side. (Javascript)
Problem/Requirement:
I want to take clients time (PST, CST etc) and send it in the corresponding server time. (Whatever timezone the server is in) (Not necessarily UTC).
My code:
I've attempted the following but still confused as where I'm going:
getServerTimeZone: function(newTime){
var _this = this;
$.ajax({
url: '/api/config/v1/system/time'
})
.done(function(data) {
if(!newTime){
newTime = new Date();
}
//Get Server Timezone and offset
//Offset is in milli sec. Converting it to hours
var serverTimeOffset = data.timeZoneOffset / (60 * 60 * 1000);
// Get current timezone offset for host device
var x = new Date();
var clientCurrentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
//Calculate the difference
var actualOffset = Math.abs(clientCurrentTimeZoneOffsetInHours - serverTimeOffset);
//Format actual time in relative to server time
serverTime = moment.utc(newTime).zone(actualOffset).format('MM/DD/YYYY h:mm A');
});
},
Please see the modified code below, i used moment js manipulation feature utcOffset so we can change the timezone of the clients date.
It will give us the corresponding server date/time based on the date/time on the client.
getServerTimeZone: function(newTime){
var _this = this;
$.ajax({
url: '/api/config/v1/system/time'
})
.done(function(data) {
if(!newTime){
newTime = new Date();
}
//Get Server Timezone and offset
//Offset is in milli sec. Converting it to hours
var serverTimeOffset = data.timeZoneOffset / (60 * 60 * 1000);
// Get current timezone offset for host device
var x = new Date();
var clientCurrentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
// change the timezone using utcOffset
serverTime = moment(x).utcOffset(serverTimeOffset).format('MM/DD/YYYY h:mm A');
});
},
You can test it here, i used -5 offset.
https://jsbin.com/puvutevomo/edit?html,js,output
If I'm understanding the requirement correctly you shouldn't need to send any timezone specific information up to the server. When a date/time is given in ISO8601 format (and has an x on the end) it is in UTC format. Timezones at that point are irrelevant and only used for display purposes.
moment will display that date/time in the user's correct timezone automatically (based on the browser settings).
var d = moment('2016-01-01T00:00:00.000Z');
console.log(d.format('llll')); //This will output the date/time relative to the user's timezone automatically
var sendToServer = d.toISOString() //send this string up to the server. It is in UTC format.

Return documents created since midnight

I want to find all document's created since midnight, regardless of the users timezone. If the users on Pacific time, it should show all their documents since midnight Pacific. Same with Eastern time.
I'm on Eastern time and this works for me:
var d = new Date();
var midnight = d.setHours(0,0,0,0); // last midnight
var count = Items.find({
username: Meteor.user().username,
createdAt: { $gt: midnight }
}).count();
But my client is on CST and it doesn't work for him. It instead shows documents created since like 10pm or 11pm CST the previous day. So this seems like a timezone issue for me.
Assuming that this is a client-side issue only (all of the times are stored in UTC on the server) then you can get the UTC adjusted time for midnight of the users current timezone by doing the following:
var now = new Date();
var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var midnight_utc = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
See this fiddle: https://jsfiddle.net/Lbk1vo0j/1/
For example, for my current time zone (eastern) I get the following values for now, midnight, and midnight_utc (when printing the Date objects using the toLocaleString() method):
3/30/2015, 3:06:39 PM
3/30/2015, 12:00:00 AM
3/29/2015, 8:00:00 PM
try setUTCHours(0, 0, 0, 0);. It gets the Coordinated Universal Time that should be the same for every user.
I had similar requirement so I did used following method,
Created function to map datetime to _id
used that id to get my data.
Function that I am using is
function objectIdWithTimestamp(timestamp){
// Convert string date to Date object (otherwise assume timestamp is a date)
if (typeof(timestamp) == 'string') { timestamp = new Date(timestamp); }
// Convert date object to hex seconds since Unix epoch
var hexSeconds = Math.floor(timestamp/1000).toString(16);
// Create an ObjectId with that hex timestamp
var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
}
using it
db.collection.find({_id:{$gte:objectIdWithTimestamp(Y/m/d H:i:s)}})
I will advice you try moment library and resolve the time zone problem. Where ever client code is getting executed, get its last midnight time, convert it to UTC time & then easily retrieve the information from MongoDb. Few moment library usage example, for more detail refer here
var str = "2013-12-01"
moment.tz(str, "America/Los_Angeles").format(); // 2013-06-01T00:00:00-07:00
moment.tz(str, "America/New_York").format(); // 2013-06-01T00:00:00-04:00
Minutes since midnight
You can get the minutes since midnight from the user's perspective. Try using it to query the server for changes since x minutes ago.
var d = new Date();
console.log(d);
var now = d.getTime();
d.setHours(0,0,0,0);
var midnight = d.getTime();
var minutes_ago = Math.floor((now-midnight) / (60 * 1000));
console.log(minutes_ago);
output:
Date {Thu Apr 02 2015 16:12:54 GMT-0700 (PDT)}
972
This should work:
var d = new Date();
var midnight = d.setUTCHours(0,0,0,0); // last midnight everywhere
var count = Items.find({
username: Meteor.user().username,
createdAt: { $gt: midnight }
}).count();

jQuery: How to convert server time in UTC to web browser's local time?

I have a server time (east cost of USA) that I want to convert to user's local time regardless of his location. I don't know the user's time zone.
Here is a sample date stored in MongoDB (UTC time):
ISODate("2012-05-03T09:40:34.764Z") which becomes 5/3/2012 5:40:34 AM
I want to convert this to local time of the user.
Is there a plugin I can look at or someone has it done w/o plugin?
This my code which is not working:
var svrDate = new Date('5/3/2012 5:40:34 AM');
var tzo = ((new Date()).getTimezoneOffset() / 60) * (-1);
var userTime = new Date(svrDate.setHours(svrDate.getHours() + tzo)).toLocaleString());
Simple:
var d = new Date("2012-05-03T09:40:34.764Z");
alert(d);
In my case, this prints:
Thu May 03 2012 02:40:34 GMT-0700 (PDT)
Because I'm in California.
The Z at the end of the string indicates that the date string is in UTC. JavaScript already knows how to handle that. If you want local time, just call the usual getTime(), getMonth(), getDay() methods. If you want UTC time, call their UTC variants: getUTCTime(), getUTCMonth(), getUTCDay(), etc.
Have a look at the jquery-localtime plugin at https://github.com/GregDThomas/jquery-localtime - that will convert a UTC time to the local time.
`//Covert datetime by GMT offset
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
date = new Date(date);
//Local time converted to UTC
console.log("Time :" + date);
var localOffset = date.getTimezoneOffset() * 60000;
var localTime = date.getTime();
if (toUTC)
{
date = localTime + localOffset;
}
else
{
date = localTime - localOffset;
}
date = new Date(date);
console.log("Converted time" + date);
return date;
}
`

Send date from client to server

I want to send data from client and create it on server. So:
1) How can I get the total milliseconds count by JavaScript Date object?
2) How can I create .NET DateTime object by total milliseconds count?
You will have to use AJAX for this. Once you send the d.getTime() as explained by the other answer, parse it like this in your C# code behind:
if (!string.IsNullOrEmpty(Request.Form["milliseconds"]))
{
long clientSideMS = Int64.Parse(Request.Form["milliseconds"]);
DateTime past = new DateTime(1970, 1, 1);
DateTime clientSideDate = past.AddMilliseconds(clientSideMS);
}
After this, clientSideDate will be the date on the client side.
Edit: using jQuery, posting the date is as simple as:
var now = new Date();
var ms = now.getTime();
$.post("Page.aspx", { milliseconds: ms.toString() } );
var d = new Date();
alert(d.getMilliseconds()); // for the milliseconds between the current seconds
alert(d.getTime()); // for the milliseconds since Midnight, Jan 1, 1970

Categories

Resources