Converting a string to a Date in Angular2 using Typescript

I need to initialize a new Date object using a specific date. I have considered converting it from a particular string, like so:

let dateString = '1968-11-16T00:00:00'

How can I achieve this in typescript?

Update:

I am specifically looking for a solution in Typescript, not regular Javascript, and in Angular 2, not the old AngularJS (1.x)

Answer №1

To display dates in a specific format, you can use the date filter.

Within the .ts file (TypeScript):

// Variables used in HTML
let dateString = '2002-07-25T00:00:00';
let newDate = new Date(dateString);

// Format date in TypeScript
getFormattedDate(date: Date, format: string) {
    const datePipe = new DatePipe('en-US');
    return datePipe.transform(date, format);
}

// Convert date to user's timezone
const localDate: Date = this.convertToLocalDate('02/10/2022');

convertToLocalDate(responseDate: any) {
    try {
        if (responseDate != null) {
            if (typeof (responseDate) === 'string') {
                if (String(responseDate.indexOf('T') >= 0)) {
                    responseDate = responseDate.split('T')[0];
                }
                if (String(responseDate.indexOf('+') >= 0)) {
                    responseDate = responseDate.split('+')[0];
                }
            }

            responseDate = new Date(responseDate);
            const newDate = new Date(responseDate.getFullYear(), responseDate.getMonth(), responseDate.getDate(), 0, 0, 0);
            const userTimezoneOffset = newDate.getTimezoneOffset() * 60000;

            const finalDate: Date = new Date(newDate.getTime() - userTimezoneOffset);
            return finalDate > Util.minDateValue ? finalDate : null;
        } else {
            return null;
        }
    } catch (error) {
        return responseDate;
    }
}

Within the HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Here are some formats that you can implement:

For the Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

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

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

Trouble Ensues When Implementing Angular 9 Template Driven Form Validation and Setting Focus to the Next Field Simultaneously

Angular 9 is used for my template-driven login form. <form name="login" #loginForm="ngForm" (ngSubmit)="loginForm.form.valid && login()" *ngIf="loginPage" novalidate> <ion-item> &l ...

The process of assigning a local variable to a JSON response in Angular 2

I need to store a JSON response that includes an array with the following data: 0 : {ID: 2, NAME: "asd", PWD_EXPIRY_IN_DAYS: 30} 1 : {ID: 1, NAME: "Admin", PWD_EXPIRY_IN_DAYS: 30} In my code, I have defined a local variable called groups of type ...

Refresh the Angular2 API at regular intervals to monitor any updates in the response

Is it possible in Angular 2 to monitor changes in the API? Here is my scenario: I upload a document to an API at /document/upload This API returns a DOC ID When I make a call to /document/DOC_ID, the API responds with JSON in this structure: "errorCo ...

Highlighting the home page in the navigation menu even when on a subroute such as blog/post in the next.js framework

After creating a navigation component in Next JS and framer-motion to emphasize the current page, I encountered an issue. The problem arises when navigating to a sub route like 'localhost:3000/blog/post', where the home tab remains highlighted i ...

Which offers a more efficient approach: implementing functionalities within subscribe or in a custom operator with RxJS?

Within my angular application, I frequently utilize a pattern like this: this._store .root .pipe( ..., mergeMap(() => this._httpClient.get<IEvent[]>(`${this.ROUTE}/user/${id}`)) ) .subscribe((events: IEvent[]) => ...

Leveraging vue-devtools in combination with the composition-api while implementing a render function (such as JSX)

Ever since I made the transition to utilizing the composition-api and incorporating a render function (primarily leveraging JSX with TypeScript for type safety within the template), I've encountered an issue where vue-devtools cannot inspect the compu ...

Sorting Angular data using database queries

I'm currently setting up a blog for my website. Everything is running smoothly with the database, but I've run into an issue with the order of my posts - they are displayed in the opposite order that I want. The oldest post is showing at the top, ...

Encountering a timeout error when trying to test the video element with Jest

My function extracts meta data such as width and height from a video element in the following code snippet: export async function getVideoMetadata( videoBlobUrl: string, videoElement: HTMLVideoElement, ): Promise<{ width: number; height: number }> ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

Choosing a value with an Ionic checkbox

Here's the coding template I'm working on: <ion-list > <ion-item> <ion-label>This month</ion-label> <ion-checkbox checked=true></ion-checkbox> </ion-item> ...

Refreshing issue: Model change in child page not updating view correctly (Ionic & Angular)

I am currently working with Ionic 3.20 and Angular 5.2.9, encountering an issue with content refreshing after a model change. Despite being new to this, I sense that I might be overlooking something fundamental. Within my view, I have the following elemen ...

Error: JavaScript object array failing to import properly

In my code, I have an array of objects named trace which is defined as follows: export const trace: IStackTrace[] = [ { ordered_globals: ["c"], stdout: "", func_name: "<module>", stack_to_render: [], globals: { c: ["REF" ...

Tips for retrieving the text from a POST request in C#

I have a basic Angular form that allows users to upload a file along with a description. constructor(private http: HttpClient) { } upload(files) { if (files.length === 0) return; const formData: FormData = new FormData(); var filedesc ...

Monitor changes in a dynamic child component using Angular fire and TypeScript only (no HTML)

Currently, I am developing a component using TypeScript and passing inputs to my child component from there. In the parent TypeScript file: this.childComponent = this.viewContainerRef.createComponent(this.data.body).instance; this.childComponent['chi ...

I want to remove an object from my Django Rest Framework (DRF) database using Angular 13

After receiving the id that needs to be deleted, I noticed that the last line of code in service.ts for the delete method is not being executed. The files and code snippets I utilized are: COMPONENT.HTML <li *ngFor="let source of sources$ | async ...

Steps to automatically make jest mocked functions throw an error:

When using jest-mock-extended to create a mock like this: export interface SomeClient { someFunction(): number; someOtherFunction(): number; } const mockClient = mock<SomeClient>(); mockClient.someFunction.mockImplementation(() => 1); The d ...

Can a discriminated union be generated using mapped types in TypeScript?

Imagine you have an interface called X: type X = { red: number, blue: string } Can a union type Y be created using mapped types? If not, are there other ways to construct it at the type level? type Y = { kind: "red" payload: number } | ...

Selecting default rows within the PrimeNg TreeTable component

Can someone assist me in figuring out how to automatically select/highlight rows in the tree table? I've noticed that the TreeNode interface doesn't seem to have any options for highlighting rows. Thanks! Provided: a default list of IDs for no ...

Encountering a NullInjectorError while running unit tests in Angular 14 specifically related to a missing provider for Untyped

After transitioning my project from Angular 13 to Angular 14, I encountered this error message: Error: NullInjectorError: R3InjectorError(DynamicTestModule)[UntypedFormBuilder -> UntypedFormBuilder]: NullInjectorError: No provider for UntypedFor ...