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
Related
I had two ical format timestamps and I want to convert them to normal time first and then to unix time.
Here this is the function I've been using to convert normal time to unix timestamp:
var normal_to_unix = function (date_string) {
var date = new Date(date_string);
return date.getTime() / 1000;
}
This function is fine since date is already in UTC and I need not do any conversions.
Now this is the function I've been using to convert ical time to unix time. The ical time in my case is like "20180603T150000Z".
var ics_to_unix = function (ics_string) {
var year = ics_string.slice(0, 4);
var month = ics_string.slice(4, 6);
var date = ics_string.slice(6, 8);
var hours = ics_string.slice(9, 11);
var minutes = ics_string.slice(11, 13);
var seconds = ics_string.slice(13, 15);
var milliseconds = 0;
console.log(year, month, date, hours, minutes, seconds, milliseconds); // This is example output 2018 06 03 15 00 00 0
return normal_to_unix((new Date(year, month, date, hours, minutes, seconds, milliseconds)).toDateString())
}
Now the problem is I'm getting the same unix time for "20180603T150000Z" and "20180603T160000Z" which are supposed to give different timestamps and it is 1530576000 for both of them.
Is there anything that I'm missing ? Thanks in advance.
Please have a look at this for live example
Several points here:
The toDateString() method returns the date portion of a Date object in human readable form in American English. For your example it is `Tue Jul 03 2018', perhaps that is not what you want.
new Date creates date in your local timezone, which could play well if you use it together with toString(), which will also return the string for date in your local timezone. But it will be subject to daylight saving changes, so I'd avoid using that method.
Another thing I'd like to avoid converting back and forth between strings and dates, since it does a lot of unnecessary computations.
I'd suggest to use the following:
var ics_to_unix = function (ics_string) {
var year = parseInt(ics_string.slice(0, 4));
var month = parseInt(ics_string.slice(4, 6)) - 1; // Jan is 0
var date = parseInt(ics_string.slice(6, 8));
var hours = parseInt(ics_string.slice(9, 11));
var minutes = parseInt(ics_string.slice(11, 13));
var seconds = parseInt(ics_string.slice(13, 15));
return Date.UTC(year, month, date, hours, minutes, seconds) / 1000;
}
I have added explicit conversion of strings to numbers, adjusted the month to match what is used in javascript and also removed the extra call.
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) ...
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();
At the moment I save my date like this: ISODate("2014-11-17T16:19:16.224Z"), but I want this result: ISODate("2014-11-16T23:00:00Z"). How can I do this?
An easier alternative is to use Date.setHours() - in single call you can set what you need - from hours to milliseconds. If you just want to get rid of the time.
var date = new Date();
date.setHours(0,0,0,0);
console.log ( date );
Set the parts you don't want saved to 0. In your example, you would set the minutes, seconds, and milliseconds to 0.
var date = new Date();
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
var isoDateString = date.toISOString();
console.log(isoDateString);
Or, a less verbose option:
var date = new Date();
var isoDateString = date.toISOString().substring(0,10);
console.log(isoDateString);
To Save a date without a time stamp:
let date = new Date().toLocaleDateString('en-US');
console.log(date)
// OUTPUT -> m/d/yyyy
Use this to find options to add as paramaters for the toLocaleDateString function
I'm trying to use jquery countdown to sync with the server so the time is the same for all visitors. The files are being hosted on AppEngine using the static settings to host the HTML. PHP doesn't work on AppEngine.
Would it be possible to sync with the server time using Python under AppEngine's static settings? - how would I use datetime.now() in Jquery?
function countdown() {
var eventTime = new Date('May 23, 2012 08:00:00');
$('#time-left').countdown({ until: eventTime, layout: '<ul class="timer"><li class="days">{dn}</li> <li class="hours">{hnn}</li><li class="mins">{mnn}</li><li class="secs">{snn}</li></ul>',
serverSync: function() { return new Date('datetime.now()') }});
}
Thanks for your help.
its difficult to calculate time in client side because its vary in different time zones.... so get the server time in UTC and create a local time variable in UTC offset, then compare sec deff in local time
// return string must be in UTC time yyyy/MM/dd H:mm:ss format in Json result
$.get("timerequestmethod", function (data) {
var dateArray = data.split(' ');
var seconds = getSeconds(dateArray);
// create countdown until 'seconds' declare in above statement
});
getSeconds = (function (dateArray) {
var dt = dateArray[0].split('/');
var tm = dateArray[1].split(':');
var times = new Date();
times.setUTCFullYear(dt[0], (dt[1] > 0 ? dt[1] - 1 : dt[1]), dt[2]);
times.setUTCHours(tm[0]);
times.setUTCMinutes(tm[1]);
times.setUTCSeconds(tm[2]);
return (times - new Date()) / 1000;
});