Weird data format from firestore db - javascript

My data from Firestore looks this way:
Timestamp(seconds=1566840930, nanoseconds=491000000)
Since it's not a valid unix timestamp i have no idea on how to display it in a readable name, like dd.mm.yy.
I'm fetching data in a component:
#Component({
firestore() {
return {
linksArray: db.collection('links')
}
}
})
Then using v-for i'm displaying a list of links.

What you have there is a Firestore Timestamp object, which is defined as:
A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time.
So (like UNIX timestamps) it represents a point in time relative to the UTC Epoch time, but (unlike UNIX timestamps) it represents this time with nanosecond resolution.
If you want to get the millisecond resolution that UNIX timestamps are in, call toMillis() on the Timestamp.

Related

How to time duration calculate in react js

I want to calculate the time duration with the current time and another time. In my problem the current time and all ready time in data base time format are different, this format is given format: 2020-11-07 , 22:52
but now time format is 30/10/2020 , 20:50:34 . So I have a problem with this diffrent format.
You can convert both values to timestamps (in milliseconds) from their own formats and then calculate the difference in milliseconds with simple math.
If you are having trouble parsing the values, you can check Date documentation. An example can be:
let birthday = new Date('1995-12-17T03:24:00')

How to get unix timestamp in nanoseconds with JavaScript?

I'm using moment and I have a datetime like 2020-11-04 21:01:54.434 in a moment object. I would like to obtain the unix timestamp in nanoseconds. I'm trying things like moment.valueOf() but they don't seem to be working up to nanosecond precision. Given that the moment object has information about the nanoseconds, is there anyway I can extract it as the number of seconds since unix epoch?
Math.round(moment.getTime() * 1000)
Because moment.getTime will return you time in milliseconds, so you have to convert it in nanoseconds

Convert timestamp from timezone to UTC timestamp?

I am receiving a timestamp from a third-party API, that looks like: 1540388730994. However, I have been informed that this timestamp is in 'Europe/Amsterdam' timezone.
I need to convert this timestamp to UTC, as we store all our dates in UTC.
How is this possible in JavaScript?
So far I have tried:
const timestamp = 1540388730994
const timestampInUTC = moment.tz(timestamp, 'Europe/Amsterdam').utc().valueOf()
console.log(timestamp, timestampInUTC)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.21/moment-timezone-with-data-2012-2022.min.js"></script>
However, you can clearly see that the two output timestamps are identical, whereas I would have expected the conversion to subtract 1-2 hours, as Amsterdam timezone is GMT+2.
What am I doing wrong here?
Timestamps in numeric form are always in UTC. If they've for some reason manually added/subtracted it by a time zone offset, they are doing it wrong. You don't see any change from moment, because a UTC timestamp is the same moment in time regardless of what time zone you represent the local time equivalent in. If you expected the timestamp to change, that would be representing an entirely different moment in time.

How to save correct time in database?

I have one object called appointment which has two properties: StartDate and EndDate.
When I make POST request I send these values using ISOString time .
this.appointment.StartDate.toISOString()
On the server-side, I received these properties with correct values. Also, it seems to be correct when I create model in order to save appointment to the database. I used .ToUniversalTime() method.
var newAppointment = new Appointment()
{
StartDate =Convert.ToDateTime(model.StartDate).ToUniversalTime(),
EndDate = Convert.ToDateTime(model.EndDate).ToUniversalTime(),
SpecialityId = speciality.Id,
LocationId = location.Id,
PatientId = patient.Id,
UserId = user.Id,
Observations = model.Observations
};
But in database I found another values. Can explain somebody why is this behaviour ?
For instance, I used 2017.09.01 11:00 for StartDate and in database i found 2017-09-01 08:00
The server and database is located in the westeurope.
A few things:
Don't call ToUniversalTime in a web application. It's designed to convert from the server's local time zone to UTC. The server's time zone should be irrelavent to your application. Web applications should never use ToUniversalTime, ToLocalTime, DateTime.Now, TimeZoneInfo.Local, DateTimeKind.Local or any other method that uses the time zone of the computer it's running on.
Ideally, on the server side, your model.StartDate and model.EndDate would already be DateTime objects, because they'd have been deserialized that way. Therefore, you probably don't need to call Convert.ToDateTime. If they are strings, then I would adjust your model class accordingly.
On the client side, assuming StartDate and EndDate are JavaScript Date objects, and they were created using local time values (that is, the time zone of the browser), when you call toISOString, you're not just getting a string in ISO 8601 format - it is also converting it from the browser's time zone to UTC.
In your example, the UTC time is 3 hours ahead of UTC for the date and time shown. From your profile, I see you are located in Romania, which is indeed UTC+3 for this date, because it is currently observing Eastern European Summer Time. When Summer Time ends (on October 29, 2017 at 04:00), it will return to UTC+2. For this reason, you cannot simply add three hours to all values.
If you want to send local time values from the client, you should send them in ISO 8601 format, without any Z or offset, for example 2017-09-01T11:00. There are several ways to achieve this:
The best way is to not have them in a Date object to begin with. For example, if your input uses the <input type="datetime-local" /> input type (as specified in HTML5), the .value property is not a Date object, but rather a string in ISO 8601 format.
If you can't avoid a Date object, then create a local ISO string, like this:
function dateToLocalISOString(date) {
var offset = date.getTimezoneOffset();
var shifted = new Date(date - offset * 60 * 1000);
return shifted.toISOString().slice(0, -1);
}
OR, using Moment.js:
moment(yourDateObject).format("YYYY-MM-DD[T]HH:mm:ss.SSS")
Lastly, you will probably read advice from others about storing these as UTC. Don't listen. The advice "always use UTC" is shortsighted. Many scenarios require local time. Scheduling appointments is a primary use case for local time. However, if you need to act on that appointment, you'll use the current UTC time, and you'll also need some information about the time zone for the appointment so you can convert from UTC to the appointment's time zone. For example, if this is something like an in-person doctor's office appointment, then it's safe to assume the time zone of the doctor's office. But if it's an appointment for an online meeting, then you'll have to capture the user's time zone separately and apply it on the back end where appropriate.
The problem is with your current timezone.
What your application does is get current timezone (+3) in this case.
Now it got your timezone but it will convert to utc time. So what will happen, your current time will be -3 hours.
If you not adjust to summer and winter time then you can simply add 3 hours to the datetime. Otherwise you have to get the offset of your timezone and add that to the current datetime value.
Take care if you use this application in different timezones. For example You life in +3 and some else life in +2 timezone.

How to compare dates with moment

I'm trying to compare dates from database (firebase) with NOW. I'm using moment.js and it's not working. I think it has something to do with the time zone (or UTC+01:00)...
Example.
date1: "2016-11-20T14:00:00"
NOW: "2016-11-20T14:49:20+01:00"
I get NOW with moment() and compare like this:
var date1 = moment("2016-11-20T14:00:00");
moment(date1).isSameOrAfter( moment() ) // returns true
The comparison is precisely one hour off... How can I fix this? AND: is there any best practice in storing and comparing dates across time zones.
Dates should always be saved in UTC. If you use string type the UTC date time value in ISO format.
So while saving convert from client time zone into UTC and while retrieving convert from UTC into client time zone.
Comparison should be done between two dates in the same time zone.
If the database value is in UTC and then you have to parse as .utc() while creating a moment object.
moment.utc("2016-11-20T14:00:00");
Change the NOW value to UTC before comparing.
moment.(date1).utc()
Alternatively you can change the database value from UTC to local.
moment.utc("2016-11-20T14:00:00").local()
Keep the NOW value as is before comparing.
You cannot compare the date you stored in Firebase with now() as it lacks the information about your timezone.
You can store dates using Firebase.ServerValue.TIMESTAMP
For Example:
date1: Firebase.ServerValue.TIMESTAMP
This will save your time in Unix Milliseconds (time since the Unix epoch, in milliseconds) by the Firebase Database servers.
Then you can compare with new Date().getTime() this will give your device time in Unix Milliseconds.
For Example:
if(new Date().getTime() >= date1) {
//do something
}
Hope it helps :)

Categories