Generating a UTC timestamp in TypeScript

I am currently facing an issue with my application where I need to ensure that it always uses UTC time, regardless of the system time. I have a method in place to create a date:

  public static createDate(date: Date = new Date()): Date {
    return new Date(
      Date.UTC(
        date.getUTCFullYear(),
        date.getUTCMonth(),
        date.getUTCDay(),
        date.getUTCHours(),
        date.getUTCMinutes(),
        date.getUTCSeconds(),
        date.getUTCMilliseconds()
      )
    );
  }

Despite this method, when the time is saved in the database, it appears to be 8 hours ahead and I'm unsure why this discrepancy is occurring.

I have attempted other solutions found on platforms like stack overflow, including using libraries such as moment and date-fns, but unfortunately, none of these alternatives have resolved the issue so far.

Answer №1

The Date object keeps the time in UTC at all times. This is because it internally stores a numeric timestamp based on UTC, representing the milliseconds since 1970-01-01 00:00:00.000 UTC. You can access this timestamp directly using methods like .getTime(), .valueOf(), or by coercing the Date object into a Number. For a string representation of it, you can use .toISOString().

Your method of copying the Date object shown in your question is unnecessary and inefficient. The same result can be achieved with new Date(date).

You mentioned encountering issues with time offsets in your database, but without seeing that part of your code or knowing more about your database, I cannot provide a direct solution. It is likely that there is an error in how you are passing the Date object into the database, resulting in conversion to local time.

Answer №2

After some investigation, I discovered that the discrepancy in the displayed time was due to my computer's manual time setting causing it to use a different time zone. I have since corrected this issue and everything appears to be working correctly now.

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

Obtain the data from a promise in Angular

I have a function that returns a Promise, and within that Promise, I receive an object in the resolve. Below is the function from my service that is functioning correctly. buscarUsuario(email: string){ return new Promise((resolve, reject) => { this.ht ...

The best approach to effectively integrate TypeScript and Fetch is by following the recommended guidelines

Currently, I am in the process of learning React and Typescript simultaneously. On the backend side, I have a server set up with ApiPlatform. For the frontend part, my goal is to utilize fetch to either create or update a Pokemon along with its abilities. ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Perfroming unit testing on base class using Jasmine and Angular framework

I have a common base class that I include in every grid component. Currently, I have the specifications for the grid component, but I want to create separate specifications for the base class in its own spec file. The goal is to eliminate redundant code ...

Variability in determining union types for matched conditional results

In my experience, I have noticed a discrepancy in TypeScript's type inference when dealing with conditional return statements in functions. I have two identical functions, register and register2, outlined below: const register = (step: 1 | 2) => { ...

The combination of UseState and useContext in React Typescript may lead to compatibility issues

I attempted to integrate the context API with the useState hook but encountered difficulties when using TypeScript. First, let's create App.tsx: const App = () => { const [exampleId, updateExampleId] = useState(0); return ( <div> ...

Is there a method to uncover the code that controls the display of a <div> element?

As a fresh face at the company, I've been given the responsibility of developing a chart that is similar to one already present on their website. While I have the knowledge and skills to create it, I am struggling to locate the specific code where the ...

Typescript's mock function allows developers to create mock implementations of

Here is the code that needs to be mocked: const P = { scripts: { getScripts: (name?: any) => { // do some stuff and return json return { foo: 'value'}; } } } export default P; The code needing ...

Having an issue with displaying the country name and country code in a table using the Angular7 custom pipe

country code: "ab", "aa", "fr", ... I need to create a custom pipe that will convert a countryCode into a countryName, such as: "ab" → "Abkhazian", "ch" → "Chinese", "fr" ...

Testing the React context value with React testing library- accessing the context value before the render() function is executed

In my code, there is a ModalProvider that contains an internal state managed by useState to control the visibility of the modal. I'm facing a dilemma as I prefer not to pass a value directly into the provider. While the functionality works as expecte ...

What is the process for transitioning global reusable types to package types within turborepo?

When creating an app within the apps folder, a global.d.ts file is required with specific types defined like this: interface Window{ analytics: any; } This file should be designed to be reusable and placed in the packages/types directory for easy acce ...

I encountered an issue with my TypeScript function in Angular, as it is unable to process multiple uploaded files

I'm having trouble with my TypeScript function in Angular that is unable to read multiple uploaded files. fileUpload(event: Event) { const self = this; this.imageUploadInp = event.target as HTMLInputElement; this.imageUploadInp.addEventLis ...

Activate TypeScript EMCAScript 6 support for Cordova projects in Visual Studio

I am interested in utilizing the async/await feature of TypeScript in my VS2015 Cordova project. I have updated "target": "es6" in tsconfig.json Although there are no errors shown in intellisense, I encounter the following error while building the project ...

How do you go about making a prop optional in Typescript based on a generic type?

In my app, I have a specific type with optional props based on a generic type: type MyCustomType<R extends Record<string, string> | undefined, A extends string[] | undefined> = { record: R, array: A } There is a function that directly uses ...

The MUI component received props that were not defined

I created a customized MUI card with the intention of applying a dark background when the darkBg prop is passed. However, I've encountered an issue where despite passing darkBg as true, the card's background remains white. To troubleshoot, I atte ...

Troubleshooting problem with TypeScript and finding/filtering operations

let access = environment.access.find(it => it.roleName == userRole); Property 'filter' does not exist on type '{ siteadmin: string[]; manager: string[]; employee: string[]; contractor: any[]; }'. This scenario should work perfectly ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

What could be causing the radio button to not be checked when the true condition is met in Angular?

I am working on an angular7 application that includes a dropdown list with radio buttons for each item. However, I am facing an issue where the radio button is not checked by default on successful conditions. Below is the code snippet from my component.htm ...

implementing firestore onsnapshotListner feature with pagination

I have a web application that needs real-time updates on a large collection of documents. However, due to the size of the collection, retrieving data without applying a limit is not feasible and inefficient. Therefore, it is crucial to implement a query li ...

Step-by-step guide on incorporating a climate clock widget into your Angular project

Is there a way to integrate the Climate Clock widget from into my Angular project? Upon adding the following code snippet: <script src="https://climateclock.world/widget-v2.js" async></script> <script src="https://climateclo ...