Obtain a date exclusively for a specified time on the current day

Is there a way to obtain a datetime for a specific time on the current day without relying on momentJS? My input is a string of the time in the format 13:45

I attempted to achieve this using the following code snippet:

const time: String = '13:45'
const result: Date = moment(moment().format('L') + ' ' + time + ':00').toDate()
console.log(result) // Invalid Date

Any suggestions on how to accomplish this without utilizing momentJS?

Answer №1

Divide the given string input into hours and minutes. Proceed by instantiating a Date object and adjusting the hours and minutes using the available Date.prototype.setHours() and Date.prototype.setMinutes() methods within the Date class.

const input = '13:45';
const [hour, minutes] = input.split(':');

const today = new Date();
today.setHours(hour);
today.setMinutes(minutes);

console.log(today);

Date.prototype.setHours() method also supports optional minutes, seconds, and milliseconds as arguments, making it convenient to modify time values with just the setHours() method.

const input = '13:45';
const today = new Date();
today.setHours(...input.split(':'));

console.log(today);

Edit:

If you are utilizing Typescript and encounter errors when using spread syntax in the second code snippet above, consider updating your code to the following format:

const input = '13:45';
const today = new Date();
today.setHours(...input.split(':').map(Number) as  [number, number]);

console.log(today);

Answer №2

var current_date = new Date();
current_date.setHours(17);
current_date.setMinutes(30);

alert(current_date);

Answer №3

To easily handle time parsing, you can utilize the moment() method

const time = '13:45'
const result = moment(time, 'HH:mm').format()

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js" integrity="sha256-ZsWP0vT+akWmvEMkNYgZrPHKU9Ke8nYBPC3dqONp1mY=" crossorigin="anonymous"></script>

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

Guide on creating event hooks within VUE 2.0 component connections

I have successfully created two dynamic components. Now, I am looking to trigger the "logThat(someObj)" method of component-two using events: $emit/$on with the arguments being passed as shown in this code snippet: Vue.component('component-one', ...

Reading and extracting data from a massive XML document using Node.js

Currently, I am facing a challenge with an XML file that is quite large - exceeding 70mb. My goal is to parse this data in Node.js for potential data visualizations down the line. After giving it some thought, I decided that converting the XML file to JSON ...

Syntax Error Unearthed: Identifier Surprise Discovered in (Javascript, ASP.NET MVC, CSHTML)

I encountered an error when attempting to remove a dynamically created HTML element by clicking the corresponding remove button. The goal is to invoke the remove method at the end of the script and pass along certain arguments. However, I'm facing iss ...

Flask url_for usage done wrong

Running a flask server serves HTML pages with scripts stored in the static folder. An example script included in the header is: <script src="{{url_for('static', filename='js/viewer.js')}}"></script> The GET reques ...

Ensure Quasar tooltip remains visible as long as the mouse is hovering over it

Utilizing the tooltip feature from to showcase text and image details. Is there a way to stop the tooltip from disappearing automatically when the mouse hovers over it? At the moment, the tooltip vanishes as soon as I move my mouse onto it. Your assista ...

Having trouble displaying dynamically added images in my jsx-react component. The images are not showing up as expected

import React from "react"; import ReactDOM from "react-dom"; var bImg = prompt("Enter the URL of the image you want to set as the background:"); const bStyle = { backgroundImage: "url(bImg)"; // The link is stored ...

Unusual layout in Next.js editor (VS Code)

My chosen formatter is prettier, but I'm encountering an issue with the way it handles simple JSX functions. Initially, my code looks like this: function HomePage() { return; <div> <h1>Hello Next.js</h1> <p> Welcome ...

Could somebody provide clarification on the functions being called in the Angular Test Code, specifically evaluate() and dragAndDrop()?

Exploring the drag and drop functionality of an angular-Gridster application using Protractor with a test code. I have some questions about the functions being used in the code snippet below. Can someone clarify the purpose of evaluate() - the API definit ...

Having trouble parsing asynchronous script with cheerio parser

Utilizing cheerio for web crawling poses a challenge when encountering websites with asynchronous scripts. When attempting to extract all the scripts from such websites, they are often missed in the process. Here is an example of the code I am currently us ...

What is the standard error function used for jQuery promises?

Is there a way to establish a default error handling function for a jQuery promise? I am running a series of functions asynchronously, and if any of them encounter an error, I want the error to be reported. Currently, this is how I have to handle it: fun ...

Is it possible to deactivate an element based on a specific string present in the URL?

<div class="custom-class1"> <div class="custom-class2" id="custom-id1">hello 1</div> <div class="custom-class3" id="custom-id2">hello 2</div> <div class="custom-class4" id="custom-id3">hello 3&l ...

Adjusting the CSS class name based on the screen size and applying styles to that class only during the "onload" event

The website I am currently developing can be found at . It is built on WordPress using the Avada theme and everything seems to be functioning correctly. The image move up effect on this site is achieved with the following JavaScript: window.onload = funct ...

"Utilizing jQuery to generate select boxes with the ability to include multiple selection options

Welcome! I have posted some HTML and jQuery code that uses JQuery 1.9.1. CODE SNIPPET $(document).ready(function () { $('#search').keyup(function () { var search = $('#search').val(); if (search.length > 2) { ...

Ways to deactivate an HTML anchor tag when the page loads

My website contains an <a> element styled as a button that I need to be disabled when the site loads. However, once a checkbox is checked, I want this a link to become clickable. While I have successfully implemented this functionality using an inpu ...

Utilizing Jest to Simulate a Class - Incorporation via Imported Module

I'm having difficulty mocking a constructor of a class from an imported module. Interestingly, it works perfectly when my mock implementation is directly inserted into the jest.mock() factory function, but fails when the implementation is imported fro ...

The JavaScript script to retrieve the background color is malfunctioning

I am currently working on developing a highlighting feature for an HTML table that will dynamically change the row colors on mouseover. Below is the code snippet I have been using, but it seems to be experiencing some issues. Any assistance would be greatl ...

I'm having trouble setting up Stripe Elements in PHP. It seems like there's a communication issue between my PHP code and my JS

New to setting up Stripe Elements, I've followed the documentation closely. Installed the necessary JS modules, included the Stripe API, and connected it to the Stripe JS. In my index.php file, PHP script is at the top with HTML and JavaScript below i ...

It seems like KineticJS is removing elements from the canvas that I would prefer to keep

My website features an HTML5 canvas where I showcase a variety of images, text, and shapes using JavaScript functions. The text and shapes are created with the following JavaScript functions: function drawGameElements(){ /* Draw a line for the ' ...

What is the proper way to define the scope for invoking the Google People API using JavaScript?

I am attempting to display a list of directory people from my Google account. export class People { private auth: Auth.OAuth2Client; private initialized: boolean = false; private accessToken: string; constructor(private readonly clientEmail: strin ...

What is the best way to obtain the id of a selected row using JavaScript?

I'm attempting to utilize the JavaScript function below to extract a specific cell value from a jqgrid upon clicking. Within the following function, #datagrid refers to the table where the jqgrid is located. $("#datagrid").click(function ...