I want to get the current date and time from the firebase. Applying the following code while console logged I got the date of 1970. How to get the current date and time?
Edited Code after getting solution
let current_date;
firebase.database().ref("/.info/serverTimeOffset").on('value', function(offset) {
current_date = new Date(Date.now() + offset.val());
current_date.toString();
});
console.log(current_date);
use below line
Date.now() + offset.val()
Then the code look like below
firebase.database().ref("/.info/serverTimeOffset").on('value', function(offset) {
var date = new Date(Date.now() + offset.val());
console.log(date.toString());
});
offset.val() does not give the current UNIX epoch. It tells you how many milliseconds the client's clock is from the Firebase server clock. In most cases this will be very small (~100ms), hence your issue.
To get current date:
firebase.database().ref("/.info/serverTimeOffset").on('value', function(offset) {
var date = Date.now() + offset.val();
console.log(date);
});
Related
I know that
var currentTime = new Date();
var currentOffset = currentTime.toISOString();
will give current date & time in IST format. Can anyone help me how to get past 2 hours date & time in IST format
To calculate a time difference, you can use a combination of the relevant get and set methods. After you get the value, you perform the desired calculation and use the result as the argument for the set.
Note that the default timezone is based on system settings. So performing such a change has no bearing on the timezone (i.e. for me the code outputs in PDT).
var time = new Date();
var currentOffset = time.getTimezoneOffset();
console.log('Current time: ' + time.toISOString());
console.log('Current offset: ' + currentOffset);
time.setHours(time.getHours() - 2);
var pastOffset = time.getTimezoneOffset();
console.log('Past time: ' + time.toISOString());
console.log('Past offset: ' + currentOffset);
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();
let's say that I have two variables: one that contains a date string (without time) and another one that contains the same date string but with time 00:00:00 like this:
var date1 = '2013-10-23';
var date2 = '2013-10-23 00:00:00';
var date1_time = new Date(date1).getTime();
var date2_time = new Date(date2).getTime()
console.debug('Date 1 time: ' + date1_time + "\n" + 'Date 2 time: ' + date2_time);
The result in the console is this:
Date 1 time: 1382486400000
Date 2 time: 1382500800000
Why aren't these two equal to the same thing? Shouldn't date1's time portion default to 00:00:00 since I did not put a time?
Thank you
I just tested it on chrome and found out that
The first one gives you the timestamp for 00:00:00 UTC
The second gives you timestamp with your current timezone.
So if you substract them you will see +-your timezone:
var date1_time = new Date(date1).getTime();
var date2_time = new Date(date2).getTime();
console.log((date2_time-date1_time)/1000/60/60); //will print the timezone difference.
You can get exact what time the first variable is considering.
var timestamp = 1382486400000;
var date = new Date();
date = new date(timestamp + date.getTimezoneOffset() * 60000)
alert(date);
It all happens because of default UTC time zone and your current
timezone.
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;
}
`
How can I convert seconds into a datetime object in javascript.
Examples:
1.3308313703571
1.6324722385401
This is from a series of points and when they occurred. I understand 1.23323 more then seconds, but I can not change the value, being pulled from an api.
You can try like this:
function toDateTime(secs) {
var t = new Date(1970, 0, 1); // Epoch
t.setSeconds(secs);
return t;
}
Info on epoch date.
You can pass unix timestamp milliseconds as an argument to the Date constructor:
const secs = 30;
const output = new Date(secs * 1000);
console.log(output);
#UVM's answer is helpful, but slightly incomplete if you're dealing with timezones (i.e. UTC vs local time). With timezones, start with UTC using Date.UTC and Date.setUTCSeconds to get a true UTC date and time.
function toDateTime(secs) {
var t = new Date(Date.UTC(1970, 0, 1)); // Epoch
t.setUTCSeconds(secs);
return t;
}
You can then use a library like Moment to convert/format it to a local timezone.
your example values have a decimal.. looking like you are trying to convert 1.something seconds into a date..
Meanwhile check this example here on the correct seconds to date conversion.. you could view their js sources.
The question seems to have already been answered but this may be helpful for those attempting to do something similar to ruby's Time.at() method.
function formatDateTime(input){
var epoch = new Date(0);
epoch.setSeconds(parseInt(input));
var date = epoch.toISOString();
date = date.replace('T', ' ');
return date.split('.')[0].split(' ')[0] + ' ' + epoch.toLocaleTimeString().split(' ')[0];
};
I dunno how it be 10 years ago, but now it can solve just doing next:
let sec = 1628618888939
let time = new Date(sec)
let normalDate = new Date(sec).toLocaleString('en-GB',{timeZone:'UTC'})
time: "Tue Aug 10 2021 21:08:08 GMT+0300 (Eastern European Summer Time)"
normalDate: "10/08/2021, 18:08:08"
If in the future u will have problems like this, I can advise read about functions that relate to your question, and solution will come.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString