Transforming Time Stamp into Date Structure

I am trying to format a timestamp into a more readable date format. Currently, the timestamp I receive looks like this:

2018-10-10T05:00:00.000Z

What I want to achieve is: 2018-10-10 05:00 PM

This is how I am querying the document containing the timestamp object:

 ListAppointments(){
    var query = firebase.firestore().collection("doctorAgenda")
    var auxint = 0;
    this.dataAux
    let auxString = '[';
    
    query.where('Deleted', '==', false).get().then(res => {
      res.forEach(item => {

        auxint++;
        auxString += '{"id":"' + item.id + '","doctorAgenda":' + JSON.stringify(item.data()) + '}';
        console.log(item);
        if (res.size != auxint)
          auxString += ', ';
      })
      auxString += ']';
      this.dataJSON = JSON.parse(auxString);
      console.log(auxString);

      console.log(this.dataJSON);
    }).catch(err => {
      console.log('An error occurred ' + err);
    });
  }

This is how I am displaying it in HTML

<ion-content padding>
    <div padding-top class="card" *ngFor="let data of dataJSON">
        <div class="card__appointment review">
            <div class="card__appointment--header">
                <h3>Cardiology appointment - {{data?.doctorAgenda?.Document?.Specialty}}</h3>
                <span>Cardiology</span>
            </div>
            <div class="card__appointment--content">
                <span>Appointment held at: {{data.doctorAgenda.Document.EndTime}}</span>
            </div>
            <ion-row align-items-center class="card__appointment--footer">
                <ion-col>
                    <span>Confirmation code:</span>
                    <strong>99887</strong>
                </ion-col>
                <ion-col col-5 center text-center>
                    <button class="btn btn-outline-secondary">
                        Review
                    </button>
                </ion-col>
            </ion-row>
        </div>
    </div>
</ion-content>

Answer №1

Hopefully this solution suits your needs. It seems that many of the methods mentioned here are akin to reinventing the wheel, as there are libraries available that can easily format dates based on a formatting string.

//dateString will be in the format '2018-10-10T23:00:00.000Z'
function computeDateString(dateString) {
    var input = new Date(Date.parse(dateString))
    var padder = function (val) {
        return pad(val)
    }
    var time = [format12Hour(input.getHours()), input.getMinutes(), input.getSeconds()].map(padder).join(':')
    var date = [input.getMonth(), input.getDate(), input.getFullYear()].map(padder).join('-')
    return [date, time, getAMPM(input.getHours())].join(' ')
}

function pad(val) {
    return (val < 10) ? '0' + val : val
}

function format12Hour(val) {
    var val = (val+1) > 12 ? val-12:val
    return val === 0? 12:val
}

function getAMPM(val) {
    return val > 12 ? 'PM':'AM'
}
//prints 09-10-2018 10:30:00 AM
console.log(computeDateString('2018-10-10T23:00:00.000Z'))

I trust this information proves useful.

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

React type error: The argument 'profile' cannot be assigned to the parameter of type 'ComponentType<never>'

I've recently started learning TypeScript and I'm struggling with this particular issue. Below is the code I'm working on. import { IProps, IState } from './types'; class Profile extends Component<RouteComponentProps & I ...

Having trouble choosing multiple options from autocomplete drop-down with Selenium web-driver in Python

I am currently in the process of automating a webpage built with Angular that features an auto-complete dropdown with numerous elements. My goal is to click on each individual element and verify if it populates all the fields below accordingly. Below is th ...

Tips for accessing FCM Intent Extras within an IONIC framework

I'm currently facing an issue with IONIC and FCM. The problem at hand is that I am sending "data" instead of "notifications" from my Node JS server to my IONIC app. Although the data is being sent successfully, I am having trouble accessing it. The do ...

"Learn how to utilize Angular to showcase an array of strings and choose a specific value for

When working in HTML, I have the ability to set the option text and send the value like this: <select id="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> </select> After sending it ...

Combining Types in TypeScript: Overriding Field Types

Can someone help me understand the behavior of this sample code? type A = { field: string } type B = { field: number } //I expect A | B is equivalent to field: A["field"] | B["field"] type AORB = A | B type AORBField = { field: A["field"] | B["fi ...

Writing a condition using *ngFor to validate two values

I am currently utilizing angular 7. Within my Component, I have a Stock Array as displayed below: private stocks:any = []; [{ "scripcode": "M&M", "open": "671.95", "high": "676.90", "low": "661.60", "exchange ...

Enhancing ES6 capabilities with Angular polyfills

While exploring the Angular documentation and various online resources about Angular, I came across a question. If all code is written in Typescript, why would we need ES6 polyfills? My understanding is that webpack eventually transpiles the code to ES5, s ...

Troubden array filtration in Angular is malfunctioning

I recently developed an angular "filter component" intended to filter an array and display its contents. The keyword used to filter the array, value, is obtained from another component through a service. While the HTML displays both the value and the entir ...

Service consumption across various components is failing to function as intended

I'm working on implementing a side navigation bar and content div. The goal is to display the innerText of the selected navigation item in the content div whenever an element in the side nav is clicked. Below is my current code setup: sidenav.compone ...

Solid Start is having difficulty executing the Create Effect feature

The function getName is successfully retrieving the name of the person with id 1 from the database, but there seems to be an issue as this code is not logging anything to the console, not even the debug console.log("running"): import { Database } from &apo ...

Is there a method to indicate type narrowing to TypeScript following an initial null/undefined validation?

After loading environment variables into my Node & Express app using 'dotenv', I take steps to ensure these values are present and of the correct type before starting the server. However, when attempting to use these variables later on, TypeScrip ...

Unable to retrieve React state within the callback function

As I work with the following components: const ParentComponent: React.FC = () => { // Setting newType to some value within the code const [newType, setNewType] = useState<any>(undefined); // Enabling addEdge to true in another part o ...

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

Leverage the template pattern in React and react-hook-form to access a parent form property efficiently

In an effort to increase reusability, I developed a base generic form component that could be utilized in other child form components. The setup involves two main files: BaseForm.tsx import { useForm, FormProvider } from "react-hook-form" expor ...

An issue occurred in the ngx-bootstrap module at line 8 of the type-checks.d.ts file, displaying the error message: "Cannot find name 'Extract'"

I attempted to incorporate bsdatepicker into my code by importing BsDatepickerModule from ngx-bootstrap. However, I encountered the following error: ERROR in node_modules/ngx-bootstrap/chronos/utils/type-checks.d.ts(8,62): error TS2304: Cannot find name ...

ReactJS - Triggering a timeout reset and reactivation with a single button press

When I click a button that has a callback function, I want it to start a timeout with a 5-second delay. If the button is clicked again within that 5 seconds, I want the timer to reset without triggering the timeout handler. The handler should only be calle ...

Effective ways to manage extensive forms in Angular 2

I have a complex form in my application. What is the most effective way to collect data from this form and transmit it to the API using Angular 5? ...

The data type 'string' cannot be assigned to the data type 'undefined'

These are the different types available: export type ButtonProperties = { style?: 'normal' | 'flat' | 'primary'; negative?: boolean; size?: 'small' | 'big'; spinner?: boolean; } export type ...

Leveraging TypeScript 2.1 and above with extended tsconfig configurations

Recently, I have been experimenting with the new extends feature in the tsconfig.json file that allows developers to create a base configuration which other modules can extend or modify. Although it is functional, it is not working as anticipated. Strange ...

Issues with the File plugin in Ionic 2

Currently, I am working on integrating Quickblox into my Ionic2 application. I have successfully implemented all the required functionalities except for file uploading. In Quickblox, there is a specific function that needs to be used for uploading files, a ...