Is there a way to set the day to start from 4am not from 12am as we all know, i'm searching for a javascript library or a method to make this available, i'm now using moment.js but I couldn't figure out how to do it.
Thanx for your advice,
Get their local time, and change the timezone to be the timezone of your server plus 4 hours. The timezone of your server is the difference in hours between your local time and GMT.
var GMTdate = new Date();
var timeZoneFromDB = 4.00;
// add or subtract from the timeZone to set it to server time zone plus 4.
// get the timezone offset from local time in minutes
var tzDifference = timeZoneFromDB * 60 + GMTdate.getTimezoneOffset();
//convert the offset to milliseconds, add to targetTime, and make a new Date
var adjustedTime = new Date(GMTdate.getTime() + tzDifference * 60 * 1000);
Javascript date functions using adjustTime will not reflect the date 4 hours later than the date of your server.
Note: the hour will be incorrect of course.
Update ... fixed local time, "their time", to GMT/UTC time.
Updated again ... it was correct the first time. I thought for a moment it needed to start with GMT time (late night due-diligence).
note: if DST is used at server location, change timeZoneFromDb to
var timeZoneFromDB = ((new Date()).dst()) ? '-04:00' : '-05:00';
with correct numbers to adjust to that time zone. Also note DST does not start on the same date universally, to handle it properly the server time zone must be known.
Related
I'm trying to get a timestamp from a specific timezone that is independent of the local time.
I want my clients from all over the world to see the exact same timestamp. Is this even possible? I don't want a solution in node.js but if there is a working library, please include it.
You can either generate a timezone independent timestamp by means of JavaScript, using Date object, or using specialized libraries such as moment.js:
const timestampMilliseconds = (new Date()).getTime();
console.log(timestampMilliseconds);
const timestampSeconds = Math.round((new Date()).getTime() / 1000);
console.log(timestampSeconds);
const timestampSecondsMoment = moment().unix();
console.log(timestampSecondsMoment)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
You say that you want to get a timestamp for a "specific time zone". If you know what the time zone offset is for that specific time zone then you should be able to get a UTC date, subtract the time zone offset from it and output a date string that should be the same on all clients. This statement should work:
var timeZoneOffset = 300; // Eastern Standard Time
var sameDate = (new Date(((new Date()) - (timeZoneOffset * 60 * 1000)))).toISOString()
new Date() should return the same time in milliseconds on all clients if the date and time of the local machines are accurate. Time zone offsets are in minutes so you need to multiply them be 60 * 1000 (60 seconds/minute times 1000 milliseconds/second) and then subtract that many milliseconds from the UTC date to get it to equal the current time in the time zone that has that offset. Then convert it to an ISO string. You can manipulate the resulting string if you want. Perhaps get rid of the Z on the end.
var dateWithoutZ = sameDate.slice(0,-1);
my question is not specific to firebase and i think applicable in general.
In my case, the mobile app (a hybrid app) runs in india and the backend is firebase using nodejs. It is a food ordering app.
When a person orders the food, we use (new Date()).getTime() in the mobile app and pass that as order date.
Every time when an order is placed, a firebase trigger updates the total day sale till that time in JSON realtime DB object. And to save the total sale we use beginning of the day as the date-time timestamp. it's calculated using:
var date = new Date()
var ms = date.getTime();
var msPerDay = 86400 * 1000;
var timestamp = ms - (ms % msPerDay);
I think this whole thing is already a mess as new Date() will give different values in the mobile app in india and on firebase server (running in US north) at the same moment.
So, what is the practice to handle dates in my situation?
When new Date() is executed, a Date instance is created with a time value that represents the current time UTC.
For hosts where the clock is accurate and the timezone setting correct, Dates created at the same moment will have the time value regardless of where the host is or its timezone setting. However, in the age of "the internet of things", the host may be any one of a huge array of devices where the clock and settings may be anything but accurate.
So you really should not rely on the client being accurate and use server times for things that matter.
When you do:
var date = new Date()
var ms = date.getTime();
var msPerDay = 86400 * 1000;
var timestamp = ms - (ms % msPerDay);
you're setting the time to the start of the UTC day. It's equivalent to:
var timestamp = new Date().setUTCHours(0,0,0,0);
For 2018-11-02, that will be: 1541116800000.
You can store that if you like, but maybe you want to store it as a human readable date, in which case:
var timestamp = new Date().toISOString().slice(0,10); // 2018-11-02 on 2 Nov 2018
may suit, but it's generally recommended to use a full string, so:
var d = new Date();
d.setUTCHours(0,0,0,0);
var timestamp = d.toISOString(); // 2018-11-02T00:00:00Z on 2 Nov 2018
Note that the UTC date is different to the local date for the period of the local timezone offset (so from midnight to 05:30 local time in India will show yesterday's date).
console.log(
new Date(new Date().setUTCHours(0,0,0,0)).toISOString()
);
I am using globalize to format datetime per locale.
var Globalize = require('globalize');
var formatter = Globalize('en-US').dateFormatter();
formatter(new Date());
It works great but I was wondering if I can format date for specific timezone. This way, it always formats date in the local machine timezone.
For example, let's say my machine timezone is PST. Can I use globalize to format date in EST?
Stolen from here
This solution works by using the getTimeOffset() (which returns the time difference between UTC time and local time, in minutes) function to find the UTC time offset of a given location and changing it to milliseconds, then performing calculations from UTC to return a time for a different time zone.
/**
* function to calculate local time
* in a different city
* given the city's UTC offset
*/
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
This solution will work, but it's simpler to express timezone in minutes and adjust the UTC minutes.
Please let me know if this works for you!
The javascript function new date() generates a date/time stamp based off the machine time at the moment that the function was called. So if the function is called by a machine that is in Alaska, it will generate a date/time stamp based on the current time in Alaska at that exact moment.
w3school.com has great references to most coding related items. You can find the answer to your question here.
This has been driving me around the twist for several days now.
The application is in JavaScript.
I'm wish to show the time in one time zone for a viewer in another time zone.
I would store the time zone offset from GMT (Daylight saving would be taken in to account with the offset) for the zone I want to display the time and date for.
I was planning on converting the time to Epoch and then adding or subtracting the offset and then convert to DD MM YYYY HH MM SS for the date calculated.
I've got to the point that I can no longer see the wood for the trees. Any thoughts on how to achieve this.
Since Dates are based on a UTC time value, you can just adjust for the offset you want and read UTC values, e.g.
/* #param {number} offset - minutes to subtract from UTC to get time in timezone
**
*/
function getTimeForOffset(offset) {
function z(n){return (n<10?'0':'')+n}
var now = new Date();
now.setUTCMinutes(now.getUTCMinutes() - offset);
return z(now.getUTCHours()) + ':' + z(now.getUTCMinutes()) + ':' + z(now.getUTCSeconds());
}
// Time for AEST (UTC+10)
console.log(getTimeForOffset(-600));
// Time for CEST (UTC+02)
console.log(getTimeForOffset(-120));
Note that the offset has the same sign as the javascript Date timezone offset, which is opposite to the typical value that is added to UTC to get the local time.
I have an application where I need to display the User profile. Now where ever the user is from India or may be Brazil. I have to display the local time of that particular location. But the user who is viewing the user profile, can brows the profile from any where in World. How can I achieve it using java script. Help will be appreciated much.
You can use the Date object
function getTime () {
var today=new Date();
var hours = today.getHours() > 12 ? today.getHours() - 12 : today.getHours();
var amORpm = hours > 12 ? "pm" : "am";
var minutes =today.getMinutes();
return hours + ":" + minutes + amORpm;
}
I don't have time to test this but it should work.
Edit:
You can't exactly set the time zone with JavaScript. However, there are ways around it with some more JavaScript. I suggest looking into the moment.js library. I believe it allows you to do what I want. You can also just use a Server Based Language such as PHP or ASP.NET.
You can get the current date and time of the viewer by creating a new Date object:
var userDate = new Date();
You can adjust that to show the date at time in some other location by either adding the viewer's timezone offset then subtracting the profile timezone offset, or adjusting the internal timevalue by subtracting the profile timezone offset.
However, you will need to account for daylight saving adjustments for profiles in those places that have them.
// Return date object for provided offset.
// Offset is the ECMAScript Date object offset
// in minutes for a timezone, e.g. UTC+1000 is -600
function getTime(offsetInMinutes) {
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - offsetInMinutes);
return d;
}
// Show time in Riyadh: UTC+0300 (offset -180)
alert(getTime(-180));