The process of switching from timestamp to date varies depending on whether you are working locally or on a server

Currently, I am in the process of developing an app using Firebase as the server and Flutter for the frontend. The situation I am facing is that when I upload a new document with a timestamp containing the current time in this format:

"timestamp": DateTime.now().toString(),

When running it on localhost, I noticed that the document saves the current time accurately. However, when running it on the cloud server, it adds 3 hours to the timestamp. I understand that this discrepancy is likely due to the UTC time zone difference, where my country's UTC is +3. The relevant line of code on the server is:

console.log(req.body.timestamp);
let timeStamp = new Date(req.body.timestamp);
console.log(timeStamp);

For instance, the output on localhost for timestamp string 2020-05-23 23:16:03.735472 was displayed as:

>  2020-05-23 23:16:03.735472
>  2020-05-23T20:16:03.735Z

However, when viewed from the server, it appeared as:

>  2020-05-23 23:16:03.735472
>  2020-05-23T23:16:03.735Z

The question remains - why does this happen?

Answer №1

This seems to be a straightforward issue with timezones. Date data types do not inherently store timezone information, but when displayed, they typically use the default timezone of the system doing the formatting. However, relying on this string format for accurate timezone information may not be wise.

It is generally not recommended to store date/time objects as formatted strings. Firestore offers a proper timestamp data type that stores values using the UTC timezone offset (+0), which is the standard for modern computer systems. It's best practice to store dates using this type and then convert them to the desired timezone on the client side. Various date utilities are available to assist with these conversions.

If you need to store the current time in a document, it is common to use FieldValue.serverTimestamp() as the value, allowing Firestore to provide the timestamp at insertion. This will return a Timestamp object on the client side, which includes a toDate() method for conversion to a native Dart format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble retrieving parameters in Firebase Cloud function

I cannot seem to figure out why this code is not working, even though it seems straightforward. Below is the snippet of my code: // Setting up cloud functions const functions = require('firebase-functions'); // Using admin to access all JSON No ...

Using Lodash to eliminate objects from a list

I have a specific model for my list, it looks like this: Animal Model id name age gender city Within the animals[] = []; array that I am working with, I need to remove the fields name, age, and gender while keeping id and city. How c ...

Display the new data from an array that has been created following a subscription to Angular Firestore

I am struggling to access the content of a variable that holds an array from a Firebase subscription. The issue I am facing is that I am unable to retrieve or access the value I created within the subscription. It seems like I can only use the created valu ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

Utilize an exported class as a type within a .d.ts file

I have two classes, ./class1.ts and ./class2.ts, with the following structure: export class Class1{ ... } and export class Class2{ ... } In my file ./run.ts, there is a function that accepts a class input function doSomething(klass: ClassType){ l ...

ESLint detected a promise being returned in a function argument where a void return type was expected

I'm encountering a recurring error whenever I run my ESLint script on multiple routers in my server. The specific error message is as follows: error Promise returned in function argument where a void return was expected @typescript-eslint/no-misuse ...

What is the process for interpreting the status code retrieved from an HTTP Post request?

When sending a POST request to a backend and attempting to read the status code, I encountered the following result: status-code:0 Below are my functions: Service: signIn(uname:string, pass:string): Observable<any> { let headers = new Headers( ...

Guide on utilizing a provider's variable in another provider within Ionic 2/3

In my code, I have a boolean variable called isConnection that is used to monitor network connection status. This variable is defined in a provider named 'network' and can be set to either true or false in different functions. Now, I need to acc ...

What is the correct way to destructure a tuple in Typescript when only certain values will be assigned to new variables?

When writing code, I frequently encounter situations that resemble the following: function example(parameter: string) { const tuple = [ "newParameterValue", "newVariableValue" ] let newVar; [parameter, newVar] = tuple; } ( ...

Tips on clearing and updating the Edit Modal dialog popup form with fresh data

This code snippet represents my Edit button functionality. The issue I am facing is that I cannot populate my Form with the correct data from another component. Even when I click the (Edit) button, it retrieves different data but fails to update my form, ...

Is it possible for variables in a component.ts file to be automatically updated without the need for an updateData()/ngOnit method to be called again within the same component.ts file

I recently started working with Angular and came across a logic issue while implementing a function using a service class in my component class. Here is the code snippet that I encountered: Link to Stackblitz app.module.ts @NgModule({ declarations: [ ...

Transforming a React component into a TypeScript Element results in an automatic 'any' type assignment due to the inability to index an expression of type 'string | number'

I am currently in the process of migrating a React component to TypeScript, but I have encountered an issue that I am struggling to resolve. I am consistently receiving an error related to accessing variantStyles[variant][color], and I cannot pinpoint the ...

What is the best approach for integrating a Material UI Autocomplete component with graphql queries?

Hello there! I'm currently working with React Typescript and trying to incorporate query suggestions into an Autocomplete Material UI component in my project. Below is a snippet of my GraphQL queries: Query Definition: import gql from 'graphql- ...

Creating Class Names Dynamically in Angular 2 Using ngFor Index

Encountering an issue while trying to generate a dynamic class name based on the ngFor loop index in Angular 2. Due to restrictions, I had to use a specific syntax as Angular 2 does not support ngFor and ngIf together on the same element. Given this setup ...

The absence of type-safety in the MUI System sx is a glaring issue

I want to ensure that the TypeScript compiler can identify typos in my MUI System sx props: import { Box, SxProps, Theme, Typography } from '@mui/material' const sxRoot: SxProps<Theme> = { width: '100vw', height: '10 ...

Is it beneficial to utilize an interface for constructing a class model?

The Interface: export interface IAddEditGeneralDictionary { Code: string; StartDate?: Date | string; FinishDate?: Date | string; Name: string; } The Realization: export class AddEditGeneralDictionary implements IAddEditGe ...

Error 2322: Troubleshooting Typescript arrow functions overloads issues

Everything seems to be working well with the code below, except for an error that occurs with the resolve constant. const resolve: Resolve Type '(param: "case 1" | "case 2" | "case 3") => boolean | "string" | ...

Leveraging the Angular (2) routerLinkActive directive to handle dynamic routes

Although my current approach works, I believe there may be a more efficient way to implement this in Angular. The situation is as follows: Imagine nested, inflected paths like /logos and /logo/:id The markup below functions as intended: <li class ...

What is the reason behind the error Generic indexed type in Typescript?

Here is a scenario where I have a specific generic type: type MapToFunctions<T> = { [K in keyof T]?: (x: T[K]) => void; }; It functions correctly in this instance: type T1 = { a: string }; const fnmap1: MapToFunctions<T1> = { a: (x: st ...

The build error TS1036 is thrown when a function with a return statement is moved to index.d.ts, even though it worked perfectly in a standard TS file

In my project using Node v14.x and StencilJS (React) v2.3.x, I encountered an issue with a test-helper file containing a function that converts string-arrays to number-arrays: export function parseNumericStringOrStringArrayToIntegers(value: string | (strin ...