andrewplummer / Sugar

A Javascript library for working with native objects.
https://sugarjs.com/
MIT License
4.53k stars 306 forks source link

Timezone offset when parsing humanized string #592

Closed gabzim closed 6 years ago

gabzim commented 7 years ago

I allow my users to send humanized strings to my API.

They can send something like ?from=5 minutes ago.

In each user I store their timezone offset, so within the API, I can know that a user is in a given timezone. Is there any way for me to override the timezone when I parse that to use the user's tz offset?

Like can I say: "5 minutes ago" with -180 minutes from utc?

Otherwise I end up using the server timezone and it might not make sense to them when they say stuff like yesterday. I don't need sugar.js to know that America/Chicago is - 0500. I already know the offset in minutes, can I customize the parse function in any way to provide the minutes from utc?

gabzim commented 7 years ago

Btw, I have used newDateInternal but even if I take a date object and change it, the yesterday date returned by sugar.js is still carrying node's timezone, so that no matter what date I returned in newDateInternal, yesterday is always: yyyy-MM-DDT02:00:00.000Z (server tz), instead of yyyy-MM-DDT05:00:00.000Z (user tz)

andrewplummer commented 6 years ago

Wow, REALLY sorry I didn't even respond once to this ticket after more than a year. Probably not much use to you now, but:

Javascript does not deal with timezones. You instead have to add or subtract minutes to "fake" timezones. Other libraries deal with this and Sugar is designed to play nice with them, but it functions the same as native JS and isn't meant to mask this. So in your case you should simply be doing something like date.setMinutes(date.getMinutes() + date.getTimezoneOffset() + myOffset where myOffset is the user's UTC offset in minutes. The getTimezoneOffset will set the date as UTC time so that myOffset can be correctly applied. Sugar has a helper function add to make this easier but the approach is the same.

I'm going to preemptively close this as after a year it's likely you're not even following anymore but feel free to re-open if this is still an issue for you.