Methods for comparing the current date and time to a specific time stored in a database

A database table contains the following values:

 "295fc51f6b02d01d54a808938df736ed" : {
    "author" : "James Iva",
    "authorID" : "JBvLC3tCYCgFeIpKjGtSwBJ2scu1",
    "geometry" : {
      "latitude" : 29.4241219,
      "longitude" : -98.49362819999999
    },
    "listDate" : 1482331706209,
    "openHours" : {
      "Friday" : {
        "closeTime" : "17:00",
        "openTime" : "09:00",
        "status" : true
      },
      "Monday" : {
        "closeTime" : "17:08",
        "openTime" : "09:00",
        "status" : true
      },
      "Saturday" : {
        "closeTime" : "17:00",
        "openTime" : "09:00",
        "status" : true
      },
      "Sunday" : {
        "closeTime" : "17:00",
        "openTime" : "10:00",
        "status" : true
      },
      "Thursday" : {
        "closeTime" : "17:00",
        "openTime" : "09:21",
        "status" : true
      },
      "Tuesday" : {
        "closeTime" : "17:00",
        "openTime" : "04:00",
        "status" : false
      },
      "Wednesday" : {
        "closeTime" : "17:00",
        "openTime" : "10:00",
        "status" : false
      }
    },
    "pPhone" : "no_phone",
    "placeAdd" : "San Antonio, TX, USA",
    "placeCat" : "Education"
  }
}

The task at hand is to determine if the place is currently open (status is true) and display a message like the following in the template:

IT'S THURSDAY 4:12PM - WE'RE OPEN!

How can this be achieved using angular2?

Below is the code used to subscribe and retrieve data from a service:

ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
        this.id = params['id'];
        let str = params['string'];
       // Retrieve Pet with Id route param
       this._placesService.findPetById(this.id).subscribe(place => {
         this.place = place; //Here should be the opening data!

       });
});
}

Answer №1

To gain insights on how to complete this task, refer to the following:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <br />
      {{ opening }}
    </div>
  `,
})
export class App {
  name:string;
  opening: string;

  constructor() {
    this.name = 'Angular2'

    this._refresh();
  }

  private _getDayName(): string {
    return new Date().toLocaleString("en-us", { weekday: 'long' });
  }

  // converts string-times into Date and checks if its opened ..
  private _isOpen(todaysOpeningData: any): bool {
    const curDate = new Date();
    const open = new Date();
    const close = new Date();

    // set opening time
    open.setHours(+todaysOpeningData.openTime.split(':')[0]);
    open.setMinutes(+todaysOpeningData.openTime.split(':')[1]);

    // set closing time
    close.setHours(+todaysOpeningData.closeTime.split(':')[0]);
    close.setMinutes(+todaysOpeningData.closeTime.split(':')[1]);

    // check if its opened !
    return curDate >= open && curDate <= close;
  }

  // check and build string ..
  private _checkOpeningHours(data: any): string {
    const curDayName = this._getDayName(); // get current day name
    const todaysOpeningData = openingdata.openHours[curDayName]; // get opening time for today with current day name

    if (!todaysOpeningData) return "ERROR!"; // there are no opening-times for today?
    if (!todaysOpeningData.status) return `IT'S ${curDayName.toUpperCase()} - WE ARE CLOSED TODAY!`; // we are closed entirely today !

    return `IT'S ${curDayName.toUpperCase()}, ${new Date().toLocaleString("en-US", { hour: '2-digit', minute: '2-digit' })} - ${this._isOpen(todaysOpeningData) ? 'WE ARE OPEN' : 'SORRY, WE ARE CLOSED'}!`;
  }

  private _refresh() {
    this.opening = this._checkOpeningHours(openingdata.openHours[this._getDayName()]);
    console.log(this.opening);

    setTimeout(() => this._refresh(), 60 * 1000);
  }
}

live-demo: https://plnkr.co/edit/R5fk7eJrltGx2zOuVhuz?p=preview

UPDATE:

Utilize the code snippet below:

this.sub = this.route.params.subscribe(params => {
   this.id = params['id'];
   let str = params['string'];

   // Retrieve Pet with Id route param
   this._placesService
      .findPetById(this.id)
      .subscribe(place => {
         this.place = place; //Here should be the opening data!

         // assuming that 'this.id' is '295fc51f6b02d01d54a808938df736ed'
         this.yourTargetVariable = this._checkOpeningHours(place[this.id]);
   });
});

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

Is there a way to create an HTML select element where each option has a unique background color, and will display properly

I want to create multiple HTML select elements with unique background colors for each option: <select runat="server" id="select"> <option value="A">White</option> <option value="B">Red</option> <option value="C">Yellow& ...

How to effectively manage errors in TypeScript using RxJS?

Exploring subscribe arguments in the official RxJS documentation has raised some interesting questions for me. For instance, what is the purpose of using error: (e: string) => { ... } to catch errors emitted by an observable? Despite this implementation ...

Select checkboxes by clicking a button that matches the beginning of a string in JavaScript

I have a form with a list of users and checkboxes below their names. Each user has a button that should select all checkboxes assigned to them. Below is the code for the dynamically created buttons and checkboxes. The included function takes the form name ...

What is the best way to restructure this deeply nested JSON information?

I'm working with the payload structure of my API and I want to format the data in a way that allows for dynamic display on the frontend without hardcoding column names. Currently, I am using DRF, axios, and react-redux, but I feel like I may need to d ...

Developing client-side components with NextJS

I want to develop a single-page landing page where users can upload videos and there's a file size limit check before the upload. In my src/app/page.tsx file, I have the following code: import React from 'react'; import FileUpload from &apo ...

How can I switch between different images using jQuery?

HTML <div class="image_rollover"> <img id="image_one" src=image_one.png"> <img id="image_two" src="image_two.png"> <img id="image_three" src="image_three.png"> <img id="image_four" src="image_four.png"> ...

Navigating through each element of an array individually by using the onClick function in React

I'm currently working on a project that involves creating a button to cycle through different themes when pressed. The goal is for the button to display each theme in sequence and loop back to the beginning after reaching the last one. I've imple ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code: {/* Mobile Menu */} <div className="lg:hidden"> <button className="flex items-center w-8" onClick={toggleMenu}> {isMobileMenuOpen ? ( ...

Do I need to use Node.js for Angular 2, or can I run it on an Apache server instead

Can XAMPP or Apache be used instead of the Node.js npm server when working with Angular 2? ...

Angular's nested arrays can be transformed into a grid interface with ease

I am looking to generate a grid template from a nested array. The current method works well if the elements naturally have the same height, but issues arise when values are too long and some elements end up with different heights. <div id="containe ...

Looking for advice on using the ternary operator in your code? Let us

In my JS file, the code $scope.button = id ? "Edit" : "Add"; is functioning correctly. I am trying to implement it in the View like this: <button name="saveBtn" class="btn btn-primary" tabindex="10">{{person.id ? 'Edit' : 'Add&ap ...

Turn off Typescript compilation in Visual Studio for a webpage

My Angular website (not a computer science project) is integrated into a solution, causing Visual Studio 2019 to generate multiple TypeScript compilation errors while working on other projects within the same solution. You can see examples of these errors ...

Jquery problem: dealing with empty spaces

I am working on a project where I need to use jQuery to disable specific input fields, like the following: $("input[value=" + resultId[i].name + "]" ).prop('disabled', true); $("input[value=" + resultId[i].name + "]" ).css({ 'background-col ...

Save a CSV file into a list, locate a specific key within the list, and retrieve the fourth value associated with that key

After thorough revision, the question now reads as follows: Take a look at this content in database.csv: barcode,ScQty, Name , Qty ,Code 123456 , 3 ,Rothmans Blue , 40 ,RB44 234567 , 2 ,Rothmans Red , 40 ,RB30 345678 , 2 ,Rothmans Gre ...

Is it possible to consolidate geometry in each frame during the rendering process using three.js?

Having recently delved into three.js, I've been experimenting with some concepts. My current challenge involves creating a line in the scene and using it as a reference for cloning and transforming. The goal is to display the cloned lines in a sequent ...

Using window.open and appending a new feature to it

Below is the code found in my index.html file: <!DOCTYPE html> <html> <head> <script> function createDialogBox() { var dialogBox = window.open("in1.html"); dialogBox.nameBox= "my little box" } window.onload = createDialogBox; wind ...

Data is not being displayed in the Angular table

Currently, I am working on developing a time tracking application as part of a project. However, I have encountered an issue while attempting to showcase all the entries in a table format (as shown in the image below). Despite having two entries according ...