How can I convert a string containing only the time in the format HH:MM to a Date object in Javascript?

I've encountered an issue with a business hours object in a mongoose schema that is meant to represent a date. When passing a JSON object and attempting to parse it into a Date as a string, I receive an error message stating: validation failed: business.businessHours.monday.startTime: Cast to date failed for value "08:00" (type string)

A potential workaround could involve using setters to add the current date along with the specified hours and minutes:

date.setHours(08);
date.setMinutes(30);

However, I believe there might be a more efficient solution to this problem. Is there a way to directly pass a date object within a JSON structure?

The JSON structure in question looks like this:

{
  ...,
  "businessHours":{
            "monday": {
                "startTime": "08:00",
                "endTime": "18:30"
            },
            ...
        }
}

The corresponding schema appears as follows:

const sellerSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    unique: true,
  },
  ...,
business: {
  businessHours: {
    monday: {
      startTime: {
        type: Date,
      },
      endTime: {
        type: Date,
      },
    },
    ...
  },
}

While I understand that conversion prior to saving is possible, I'm still searching for a method to directly parse a string in the format hh:mm to a date. If not, would altering the data representation through a different object type be advised, such as using numbers instead of dates for hours and minutes?

Your insights are much appreciated.

Answer №1

Whether you use values such as "18:30" or 1830 doesn't have a significant impact. Both are equally flawed.

Values like "18:30" are strings and cannot be converted into a Date. To achieve this, a full date/time string such as "2022-05-06T18:30:00" is required. Storing date values as strings is considered a design flaw; it's advisable to always store them as proper Date objects!

Using weekday names is not recommended as MongoDB does not natively support (localized) weekday names. Dynamic field names are also indicative of poor design.

The suggested approach would be:

{ 
   businessHours: [
      { dayOfWeek: 1, startHour: 8, startMinute: 0, endHour: 18, endMinute: 30 },
      { dayOfWeek: 2, startHour: 8, startMinute: 0, endHour: 18, endMinute: 30 },
      ...
      { dayOfWeek: 5, startHour: 8, startMinute: 0, endHour: 18, endMinute: 30 }
   ] 
}

According to ISO-8601, weeks start on Monday, meaning dayOfWeek: 1 corresponds to Monday.

This structure allows for easy creation of Date values, for example:

{
    $dateFromParts : {
        'isoWeekYear': {$isoWeekYear: "$$NOW"}, 
        'isoWeek': {$isoWeek: "$$NOW"}, 
        'isoDayOfWeek': "$dayOfWeek",
        'hour': "$startHour", 
        'minute': "$startMinute"       
    }
}

If using weekday names, handling them would require $switch or the utilization of third-party libraries like moment.js, luxon, or Day.js.

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

Accurate request for organizing data by user on a monthly basis

Within my MongoDB collection, I store documents with the following format: "name" : "Username", "timeOfError" : ISODate("...") This collection serves as a log to track which users encountered errors and when those errors occurred. My current goal is to ...

Tips for creating a MongoDB query with $all and $in$filter

Seeking assistance with a MongoDB query. I am looking to verify that all elements in one array exist in another array. The query should resemble the following - db.getCollection('Transactions').find({ BusinessUnitids: { $all: ...

Reduce the length of the text to 50 characters after the current word, while ensuring that the word

Looking for a way to shorten text after reaching 50 characters, making sure not to split words in the middle when cutting off. For example: Contrary to popular belief, Lorem Ipsum is not simply text (59 chars) Desired output: Contrary to popular belief, ...

Tips for incorporating JavaScript code into back4app.com using Objective-C:1. Start by accessing the

Currently, I am trying to retrieve "ServerDate" from back4app.com using PFCloud. Unfortunately, I have encountered the following issue: Invalid function: "getServerDate" (Code: 141, Version: 1.13.0) When I attempted to use the code below: [PFCloud ...

Ensure that you accurately maintain object ids following the creation of elements using ng-repeat

I have a set of items listed with unique objects within my controller $scope.itemsList = [ {"id": 0, "item": "sw", "category": 'A' }, {"id": 1, "item": "mlr", "category": 'B'}, {"id": 2, "item": "lvm", "category": 'C&a ...

Retrieve specific JSON elements and showcase on an HTML webpage

I created a simple webpage where users can input the name of an actor and I want to show all the movies that actor has been in. Currently, I have hardcoded the API URL for Bradley Cooper. How can I retrieve all movie titles, release years, overviews, and ...

Difficulties in Configuring Testacular Integration with Jasmine and Angular

I'm in the process of setting up a unit testing environment for my project and encountering some difficulties. Specifically, I am attempting to utilize Testacular with Jasmine to test my AngularJS code. One of the challenges I am facing involves a mo ...

Tips for concealing an input IP Address in React

Looking for suggestions on an IP Address mask input solution. The format might vary between 999.99.999.99 and 99.9.99.9, but react-input-mask does not support varying lengths. Any recommendations? ...

What is the reason for the compatibility issue between Vue-lang and filters?

I have implemented vue-lang from https://github.com/kvdmolen/vue-lang, but I am facing some issues. PROBLEM There is an example in the JSON file: "messages": "You have {0} {1} messages" Following this example, I added a filter to my code: <p>{{$ ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

Shader in THREE.js designed to accommodate ControlNet for normal calculations

Is there a way to adjust this standard shader to bypass the preprocessor for controlnet? Check out the code here: https://jsfiddle.net/lunchie/mpuanxL3/4/ skinnedMesh.material = new THREE.ShaderMaterial( { vertexShader: [ '# ...

Stack of Error Messages on jQuery AJAX Form Submission

How can I prevent the display of multiple error messages in my form with required fields? Currently, when attempting to continue without entering anything into the required fields, a new error message is created underneath the previous one. What steps sh ...

Changing the names of nested columns in R

I am interested in generating a json file that follows a specific schema: col1, col2, fields{name, value} Within my data frame, I have columns col1 to col4. My goal is to nest col3 and col4 under "field" and include the column name and its corresponding v ...

Storing a Class Instance in Vue Data

I am currently incorporating PDFtron into a Vue component. To display the PDF viewer iFrame upon loading the Vue, I am initializing the instance in the mounted hook: mounted() { const viewerElement = document.getElementById('viewer'); th ...

The data within a Vue.js component is interconnected with the data of other components

I have a component that looks like this. export default { name: "ImagesGallery", data () { return { activeImageIndex: 0, }; }, } This specific component serves as an image gallery. I now have another component wher ...

Error Detected: the C# script is not compatible with Javascript and is causing

I am facing an issue where I can successfully send information from the database, but I am unable to load the table on the page. When I check the data received with an alert, it appears to be in JSON format, but it still displays the wrong image on the web ...

What is the best way to update the current route in Angular 2 programmatically?

In my Angular 2 application, I am facing an issue with the navigation flow between the home component and the nav panel component. When a user clicks on the logout button in the nav panel, the current URL is correctly shown as "/login" in the console log. ...

Passport.js - Displaying error message upon access failure following a 401 status code

Currently, when I utilize done(null, user, {message: 'ok'}) in a post request, I can access the message via req.authInfo as shown below: app.post('/reg', passport.authenticate('local-reg', { session: false }), function (req, ...

Customizing tooltip text in Google Chart API: A step-by-step guide

http://code.google.com/apis/chart/ <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> // Loading the Visualization API and the piechart package from Google. google.load(' ...

Angular application - handling backend response when the object is null

I am using Angular for the front end and have a nested object structured like this: { "id": 3, "name": "Mary", "sex": "FEMALE", "currentPlane": { "airline": "american a ...