I got a timestamp from the database and I need to display its time in the user's timezone.
Ex: Brazil 16:42, France 21:42.
It's a chat, so the messages need to be displayed in each user's time zone.
I have luxon in the project, but I can not use any of the documentation that helps me in this case.
I have tried to use the methods in some ways
DateTime.local() and
DateTime.setZone(localZone)
localZone is a variable that receives the local area, for example: "Europe/Paris".
Thank you!
You can simply use luxon fromMillis to parse timestamp (assuming that it is in milliseconds) or fromSeconds if it is in seconds. You can also pass zone option to create luxon object using given timezone. The you can use toFormat() to display time in your desired format. You could have something like the following:
DateTime.fromMillis(timestamp, {zone: localZone}).toFormat('HH:mm')
If you need, you can also use setZone to change zone property, here a snippet using sample data:
const DateTime = luxon.DateTime;
let curTimestamp = 1562061791000;
let time = DateTime.fromMillis(curTimestamp)
console.log('Local time:', time.toFormat('HH:mm') );
console.log('Brazil time:', time.setZone('America/Sao_Paulo').toFormat('HH:mm') );
console.log('France time:', DateTime.fromMillis(curTimestamp, {zone: 'Europe/Paris'}).toFormat('HH:mm') );
<script src="https://cdn.jsdelivr.net/npm/luxon#1.16.0/build/global/luxon.js"></script>
If you want to use Luxon inside Angular view have a look to luxon-angular.
Related
We have a check-in and check-out component in our web app that simply uses firebase timestamps. However, we need the ability to edit those timestamps in the event someone makes a mistake.
checkInTimeStamp: fb.firestore.FieldValue.serverTimestamp("17:00") simply returns the current time.
Instead of 17:00, what object do we need to pass through the function to get the correct timestamp?
The serverTimestamp() generates current timestamp on server side. You can use a Date object instead to store a future date:
const futureDate = new Date();
// update date to future time
futureDate.setDate(futureDate.getDate() + 5);
db.document('col/doc').set({ checkInTimeStamp: futureDate })
Checkout other method like setDate() in MDN docs.
I recently tried to assign a new date in MongoDB, but I have a problem with that, it stored the date I give but it's not correct
userSchema.methods.createPasswordResetToken = async function () {
this.passwordResetToken = crypto.randomBytes(20).toString('hex')
this.passwordResetExpires = moment().format(this.createAt)
await this.save()
console.log(moment().format(this.createAt)) // 2021-12-21T19:01:54+02:00
console.log(this.passwordResetExpires) // 2021-12-21T17:01:54.000Z
return { token: this.passwordResetToken, userId: this._id }
}
mongoDb remove 2 hours when storing it
and when I try to catch the type of two values
I got
console.log(moment().format(this.createAt)) // string
console.log(this.passwordResetExpires) // object
:
user Schema
...
passwordResetToken: String,
passwordResetExpires: Date
...
From the docs:
MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.
It seems your server just sits in GMT timezone ( utc +2, you could also see it from your date value // 2021-12-21T19:01:54+02:00 ). I would usually offer some hacky way to get around the issue but this is actually a best practice. Hence I recommend you do your date calculations in UTC and not in machine time.
note your other date is in UTC (2021-12-21T17:01:54.000Z), make sure your comparing apples to apples.
I have initialized a real time database using firebase, I am detecting live changes to the databse using
const ref = firebase.database().ref("test");
ref.on('value', function(dataSnapshot){
console.log(dataSnapshot.val())
});
But this returns me value in ascending order. Whereas I want it to return based on time. I tried using time in: 00:00 (IST) format but if a data is marked 11:59 (am) and another 01:02 (pm) this will return me the second message first.
What will be the best way to fix this?
example data is =>
in my databse =>
It is not clear what you mean by time in ascending order
None of your example data mention time. They are just usernames and text.
If you want to order times correctly, best to use ISO date format
This stores 1:02 pm as 13:02, which will sort after 11:59. Its sorting characteristics are ideal.
Use an international time standard to store your times
An international time standard, UTC, has great advantages over national times. It is not subject to change with location, political decisions, or season. You can always interconvert with the user's local time, at the time of entry or display.
Example
const dateString = (new Date()).toISOString();
console.log(dateString)
// Result:
// 2021-06-22T14:40:37.985Z
// If you want to use them as Firebase keys, they must not contain a ".", so you might clean it up like this:
const cleanDateString = (new Date()).toISOString().replace(".","-")
console.log(cleanDateString)
// Result:
// 2021-06-22T14:47:44-445Z
Even better, use a Firebase PushID
The above date-and-time system will work if you are using it to sort the remarks made by a single person, but will not be good as a message identifier if a single space is shared by all people, since 2 people will eventually make a message at the same millisecond, and will get the same message ID.
To deal with that it is better practice to use a Firebase Push ID.
An explanation is given here: In Firebase when using push() How do I get the unique ID and store in my database
Or from Firebase itself, here:
https://firebase.google.com/docs/database/admin/save-data
Consider the code :
let now = moment();
console.log(now.format()); // 2019-11-25T20:23:50+02:00
console.log(now.toDate()); // 2019-11-25T18:23:50.916Z
This is the output on my local machine , and when I check the app on Heroku
it gives the same values , even though I changed the TZ like this :
heroku config:add TZ="Asia/Jerusalem"
How can I get a JavaScript Date (Not a String !) object of my localtime , meaning 2019-11-25T20:23:50 ?
Let's walk through your code example:
let now = moment();
You create a Moment object. You don't pass any parameters, so it is initialized using the current timestamp (as if you called Date.now()) and set to "local mode".
console.log(now.format()); // 2019-11-25T20:23:50+02:00
By calling format, you ask the Moment object to produce a String. Since it's in local mode, the offset that applies to that moment in time for the local time zone is emitted in the result, and the wall time shown in the result is adjusted for that offset. In this case, the local time is two hours ahead of UTC. You then pass that string to console.log, which emits it to the console.
console.log(now.toDate()); // 2019-11-25T18:23:50.916Z
By calling toDate, you ask the Moment object to create a Date object. The "mode" of the moment object is no longer relevant because Date objects don't track anything other than a timestamp. Thus, the timestamp within the Moment object becomes the timestamp for the resulting Date object. Since you derived the Moment object from the current time, the result is the same as if you just called new Date() to begin with.
You then pass the string to console.log - except one can't just log an object, so it first has to convert it to something so you can see it. Here's the interesting part: There is no spec for this behavior. Implementations of ECMAScript can do whatever they like in this regard. Some implementations, like in your example, will call .toISOString() and log the result. Since .toISOString() displays the result in UTC, the result of logging a Date object is also shown in UTC. But other implementations will call .toString() on the Date object and log that, the result being in local time. It's entirely possible some future implementation could show the result in some graphical or interactive output. The point being, you can't rely on the behavior of console.log(Date) to be consistent.
No amount of changing your time zone settings will change this result. The Date object is inherently UTC-based, your output is also UTC-based, and UTC is the same over the whole planet (by design).
If you want the time zone reflected in the string output, you must use a function that produces a string with respect to local time. As you showed, you'll get that with .format() on a Moment object in local mode. You can also get one from calling .toString() on a Date object (but the resulting string is not in the same ISO 8601 format).
i would try,
moment().local().toDate()
but if you are planning to save date into db it's good practice to save time in UTC format for easier global conversion.
If you want to work timezones you may require also moment timezone package - https://momentjs.com/timezone/docs/
npm install moment-timezone
Hope this helps :)
I have a table in my psql database with a "trigger_time" column of type "TIMESTAMP WITH TIME ZONE DEFAULT now()"
I data in the row is this 2018-06-27 15:45:00-03.
When running from psql console
SELECT trigger_time AT TIME ZONE 'UTC'
FROM tasks
WHERE task_id = 1;
this query returns "2018-06-27 18:45:00".
Similarly when I run
SELECT trigger_time AT TIME ZONE 'America/Glace_Bay'
FROM tasks
WHERE task_id = 1;
I get 2018-06-27 15:45:00
Using knex.raw("SELECT trigger_time AT TIME ZONE 'America/Glace_Bay' FROM tasks WHERE task_id = 1") I get 2018-06-27T18:45:00.000Z and when running knex.raw("SELECT trigger_time AT TIME ZONE 'UTC' FROM tasks WHERE task_id = 1") I get 2018-06-27T21:45:00.000Z
Both of these results from knex are incorrect, how do I get knex to stop silently altering my data?
Probably things are failing because when you are querying datetimes from database in certain timezone and effectively converting type of timestamp to be timestamp without timezone. In that case database will not send information to knex about in which timezone that returned time was.
So knex (or rather pg driver which knex is using) interprets your timestamp as local time, which depends of timezone setup of your application server running knex.
You could fetch time just as UTC and do timezone conversion in JavaScript side with moment or luxon libraries (IMO latter is better for timezone handling).
Other solution would be to tell pg driver that timestamp and timestamp with timezone types should not be converted to JavaScript Date objects.
It can be done like this (https://github.com/brianc/node-pg-types):
const types = require('pg').types;
const TIMESTAMPTZ_OID = 1184;
const TIMESTAMP_OID = 1114;
types.setTypeParser(TIMESTAMPTZ_OID, val => val);
types.setTypeParser(TIMESTAMP_OID, val => val);
This code which makes all timestamps to be returned as strings may be added to for example in start of knexfile.js. Those returned strings will be exactly in the same format that they were returned by database server itself.
EDIT:
In code in the original post, when timestamp is converted to be in time zone UTC database server converts timestamp with time zone type to be normal timestamp without time zone so returned value doesn't have timezone information. To add timezone information back you can for example append +02 to the end of returned time stamp like this:
select ('2010-01-01T00:00:00.000Z'::timestamptz AT TIME ZONE 'UTC')::text || '+00';
Which returns 2010-01-01 00:00:00+00 to the driver which can be read correctly by pg driver too.
This will effectively do the same thing that just setting SET TIME ZONE 'UTC'; in db server when connection is created and just returning timestamptz column directly:
SET TIME ZONE 'UTC';
select '2010-01-01T00:00:00.000+02:00'::timestamptz;
Which will return 2009-12-31 22:00:00+00.