How do I convert a new Date() into the client's time? - javascript

I'm trying to get
date = new Date()
and then make it into a local time from the client, how would I go about doing that?
I would need the Date, in this format
Day[Mon,Tues, etc.], Day of the month[18], Month[Nov,etc.], Year, then the time in either a 24 hour format or a 12 hour format, seconds would be good.
I've tried using the getTimezoneOffset(), but I'm not sure how to use it.

Dates in JavaScript should always be in the format of the client computer.
If toLocaleDateString isn't working for you, I recommend Moment.js
Using toLocaleDateString:
console.log(new Date().toLocaleDateString());
Using Moment.js:
console.log(moment().format('llll'));

By a "local time from the client" I assume that your server returns some time from, let's say, GMT-0 , and your client is at GMT-3.
Knowing your server timezone, you could do some trick to do the math using jsTimezoneDetect (http://pellepim.bitbucket.org/jstz/).
And regarding the statement "Dates in JavaScript should always be in the format of the client computer.", that's assuming you are using Javascript on the client side, while in fact, you could be using it on the server (nodes).
BTW, when you say "I'm trying to get date = new Date()" I'm assuming you're doing that on the server with nodejs, otherwise, both jasonscript and Loper324 are right, you are already in the client so that Date will be in the timezone of the client. Or were you referring just to the formatting?

Related

How to convert UTC time on server side to be users local time on a GET request?

I am trying to check if the date of the last time an element was clicked is equal to the current date. The current date is being created by the server and is 5 hours ahead of my local time, so at a certain time of day, the code stops working correctly because the program thinks it's now the next day.
Here is the code that is causing issues on my server side:
let todaysDate = new Date().toString().split(' ').splice(0, 4).join(' ')
let todaysDateMs = new Date(todaysDate + ', 00:00:00').getTime()
Promise.all([
Habits.updateMany({}, {
$set: {
todaysDate,
todaysDateMs
}
}),
Habits.updateMany({ lastClicked: { $ne: todaysDate } }, {
$set: {
clicked: 'false'
}
}),
The date that is being stored inside todaysDate is in UTC time and is 5 hours ahead. When it compares lastClicked (which is sent along with a PUT request from the client side in their local time) to todaysDate, it is setting clicked to false incorrectly because of the discrepancy between the timezones.
I am wondering if I can tell the server to create a date in the users local time or any way that I can work around this issue so that the two dates are the same. I don't want specific timestamps included, only the day, month and year.
Have you tried something like Moment.js? It makes dealing with things like this a lot easier. Check out their documentation or tutorals like this.
Generally, times on servers are done in UTC and only at the client is it converted to/from their time zone. This removes the need for the server to know anything about the client's time zone.
The client will need to send their time zone along with the lastClicked time. Then your server can read this time and adjust for time zone automatically. One example is to send the time in ISO 8601 format 2023-02-07T18:25:19-05:00 where the -05:00 indicates that this time is 5 hours behind UTC.
Alternatively, the client can pre-convert the timestamp their sending to UTC. JavaScript provides ways to do this, as do libraries such as Luxon.
Date values in MongoDB are stored as UTC time - always and only. You should never store date/time values as string, it's a design flaw.
I your case I suggest a 3rd party library like moment.js, Luxon or Day.js
They provide functions like DateTime.now().setZone('America/New_York').startOf('day').toJSDate();
With these functions it should be fairly easy to solve your requirements.

The date 2019-04-01T00:00:00.000Z gives me previous month (March, not April)

So, I have the 1st day of month as 2019-04-01T00:00:00.000Z
When I use moment(date).month(), it returns me 2, not 3.
So, I receive March, not April.
What is the problem with it, and why I receive the previous month from the date? Maybe the problem in the TimeZone? Because my TimeZone is GMT-4, so, maybe this is problem?
Should I use UTC or ISO string instead to work with the date?
Like you mentioned, your timezone is GMT-4. The date that you are providing is in UTC. The 'Z' at the end stands for Zulu time, which is the same as UTC.
momentjs will convert this to local time.
How to handle this all depends on what you need the date for.
If this is a date that you saved somewhere before on a server, it might be important to add the correct timezone to it when you are saving it.
Be careful if you let a server create these dates, because the server might be running in a different timezone than your client.
If you create a new Date() in JS it will return a date object with the current time of your local time. If this happens on a server that's running in a different timezone, or in UTC (for example Docker containers), it will create a date in that timezone.
The best way to solve this is to think about your exact use case.
There are tons of articles written about handling dates and it's not easy.
If you have some time, this podcast helps to explain how dates work and will help you to get a better understanding of dates in general:
Coding Blocks - Why Date-ing Is Hard

sending javascript date object to server without adjusting for time zone difference

Is there a way to send data from the client to a server without adjusting the time to account for the time zone difference between the client and server?
I have an angular app with a nodejs server. When I send a date from a form to the server via an HTTP request and log the date on the server, the date changes to the time in the time zone of the server.
I'd like to send the date object back and forth without it changing.
I always use http://momentjs.com/ when dealing with javascript dates. When a date object is created the systems timezone is used, so you'll always have to adjust for the offset. The easiest solution is to do one of the following
use a string and parse it
use moment().format() with a custom format
use UTC on the client and server
use ticks or unix epoch
There really isn't a great solution, you just need to be consistent.
Use milliseconds .
let now = new Date();
let time = now.getTime();
time contains number of milliseconds in UTC timezone always. In the server you can convert milliseconds to date . This way you dont need to worry about timezones.
According to MDN Javascript Date objects are constructed using UTC.
You can send the date object back and forth without ever changing it, it will simply be interpreted relative to the 'locale' of wherever it is being used.
If you'd like to maintain the local date and time irrespective of location (between different client and server locations) you'll probably need to pass along the locale of the Date as well as the Date itself.
A way to do this is to format your Date as a string in ISO 8601 format with a time offset (like +0100.)
That way you'll get both the local time and the offset used for every time.
You can construct it by hand using the Date.prototoype.toISOString method but that will still be relative to UTC.
Here's another Stack Overflow question on how to get the correct offset yourself.

Deal with timezones in JS from UNIX timestamp

I'm currently writing a small messaging app for global usage. I'm going to store the UTC timestamp of the message. I need to display the message to the user using AJAX, so i need to convert the UNIX timestamp to the users local time. I know how to get the timezone offset, but i'm afraid that it will be a little bit inaccurate and i need accuracy even in seconds (to display times like: 34 seconds ago). Which is the most accurate way to solve this?
Why not calculate the local date locally? Constructing a date with new Date(millisecondsSinceEpoch) locally and then calling toTimeString() (or whatever) should show you the local time:
new Date(milliseconds).toTimeString()
var d = new Date((new Date(1390312399000)).toUTCString());
Where the timestamp is the stored UTC timestamp.

Identifying the date format in the client's machine

I have a requirement in my project to show a date in the client machine format. I am aware of the property in javascript window.navigator.userLanguage or window.navigator.language.. But it is only returning the language of the client machine like 'en-US', 'en-GB' etc.
If the user customizes the date format of the machine for eg:-dd-MMM-yyyy, is there any way to get that format in Javascript?
Thanks in advance
suhaib
You can use the .toLocaleDateString() method:
var yourDate = new Date();
alert(yourDate.toLocaleDateString());
This doesn't tell your code what the user's selected date format is, but it lets you display a date in whatever the user's format is.
On my PC the above alerts "Tuesday, 26 June 2012".
The .toLocaleTimeString() method does the equivalent thing for the time.
The .toLocaleString() method displays date and time.

Categories

Resources