JavaScript Date Formatting Ignore Time Zone - javascript

I am working on a node.js app that is pulling a date from a sql server database, the date comes out of the database correctly, but when processed in the javascript it ends up a day prior. I have tried manually parsing the date, the date-format package and moment.js all of which take a day off. I initially thought it was time zone related after I tried a datetime variable and it was off by 5 hours. So my theory was that it was incorrectly assuming time zone. However my timezone is EST which is UTC-4 currently.
Code
const m = require('moment')
const callDate = m(summary.callDate).format('MM/DD/YYYY');
console.log(summary.callDate)
console.log(callDate)
Output
2019-10-21T00:00:00.000Z
10/20/2019

I think it may be applies the server timezone by default. So to unify all dates you may want to use moment.utc(dateObject).format();

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.

Dealing with time in different timezones react/javascript (PST/PDT)

So I have this use case where a user should be able to enter data into a react site having an order_fulfilment_datetime_str which is supposed to be a RFC 3339 datetime string according to the specs of the api this would be posted to.
So essentially a user(in any timezone) selects a (future) date and time (using a plugin such as react-datepicker) assuming that the date time is going to be in PST/PDT.
But the plugin and javascript date object returns the selected date time in the browser's timezone. So I have two things to solve:
How do I make sure that selected date/time is in PST/PDT
How to deal with DST?
Currently what I am trying to do is to simply get individual date, hours, minutes using getHours(), getMinutes(), getDate() to form the string. But again then how will I find out if this selected datetime has offset of -8 or -7(i.e. PST/PDT)?
I checked date-fns and date-fns-tz library but was not sure how to solve this issue using these.
You can use luxon library for setting a global timezone that you want, and then whenever a user selects a date-time using a date-time picker you can simply convert that into the timezone you want.
import { Settings } from "luxon"
Settings.defaultZone = <time-zone>
The above code snippet will set a default zone for the app
Now when a user selects a date-time convert it to the timezone you want using the below code
DateTime.fromISO(dateTimeValue, { setZone: true})

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

How to properly compare UTC dates against Local date in LINQ to Enitites?

I am having trouble getting data on a specified date using LINQ.
My dates are stored as UTC in the SQL database (DateTime.UtcNow).
I want to get all records for a date I or a user specifies on the browser (from a datepicker).
I am based in Australia and my database and site is hosted in another timezone and having trouble getting the results correctly.
I have tried using timezoneOffset from JavaScript and passing it to my controller to try converting UTC with the below code but still gives me incorrect results:
myRepo.Where(x => x.Date.AddMinutes(-(timezoneOffset)).Date == date.Date)
I've been scratching my head for almost 2 days already and haven't found a clear and proper solution online.
Help! :)

Date format on client browser

I am getting a date from the server as a javascript string(GMT) or unix timestamp(GMT).
I can convert it to a javascript date object with
var date = new Date(string) or var date = new Date(string)
This gives me the date variable with proper system time-zone's time.
Currently I am displaying this- date.toLocaleString()
Which gives me a nicely formatted date/time according to my system locale and time zone.
I am using this to automatically accomodate for DST if the client browser follows it.
Previously I was required to display this date only in EST, but when the US time started following EDT, I was told to display it in EST. I think this approach would simplify displaying the time/date acoording to user's system time setting.
Is there any disadvantage or possible bug accociated with this approach?
If yes, what would be the best way to display this date in the browser, so that it displays correctly according to the timezone(accomodating DST if any) in which the user(cient browser) is?
As pointed out in the comments, the output may be different depending on the users settings. A more reliable and flexibe solution is moment.js, which is a great library.
moment("2013-04-04", "YYYY-MM-DD").format("MMM Do YY"); //"Apr 4th 13"

Categories

Resources