Attempting to remove certain characters from a given string

let currentDate = new Date();
currentDate.toLocaleString;

If I were to console log the value of currentDate, it would show:

Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time)

However, what if I only want to display the minutes and seconds like 57:22? How can I achieve that?

Answer №1

Here is a challenge for you

const getTime = (str) => str.match(/:\d{2}:\d{2}/)[0].slice(1); 

// test cases
const myTime = new Date(2019,09,16,23,59,59,999);
let timeStr =  myTime.toLocaleString();
console.log(getTime(timeStr))
timeStr = "Wed Oct 16 2019 15:57:22 GMT+0300 (Israel Daylight Time)"
console.log(getTime(timeStr))

Alternatively, you can try this

const pad = (num) => ("0"+num).slice(-2);
const currentTime = new Date();
console.log(`${pad(currentTime.getMinutes())}:${pad(currentTime.getSeconds())}`)

Answer №2

If you want to display the current time using JavaScript, you can utilize the built-in methods of the Date object:

let currentDate = new Date();

let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();

console.log(minutes + ':' + seconds);

To ensure that the output is easily readable, you can add a leading zero to the minutes and seconds if they are less than 10:

let currentDate = new Date();

let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();

minutes = minutes < 10 ? ('0' + minutes) : minutes;
seconds = seconds < 10 ? ('0' + seconds) : seconds;

console.log(minutes + ':' + seconds);

Answer №3

If you're looking to work with dates in JavaScript, there are a few options available:

var myDate = new Date();
var formatted =`${myDate.getMinutes()}:${myDate.getSeconds()}`;
console.log(formatted);

Alternatively, you can also utilize the moment.js library for date formatting:

var myDate = new Date();
var formatted = moment(myDate).format("mm:ss");
console.log(formatted);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></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

What factors contribute to a one-hour discrepancy between two time stamps, deviating from the anticipated value?

Let's consider the dates '2022-04-01' and '2022-05-15'. When I calculated their deviation using Chrome devtools, here are the results: https://i.stack.imgur.com/tSZvk.png The calculated result is 3801600000. However, when my frie ...

Is it possible to create a bot that's capable of "hosting events" using Discord.js?

I am searching for a solution to host "events" using Discord.js. After some research, I stumbled upon this. Although it seems to be exactly what I am looking for, the website does not provide any code examples to help me try and replicate its functionali ...

Tips for effectively managing loading and partial states during the execution of a GraphQL query with ApolloClient

I am currently developing a backend application that collects data from GraphQL endpoints using ApolloClient: const client = new ApolloClient({ uri: uri, link: new HttpLink({ uri: uri, fetch }), cache: new InMemoryCache({ addTypename: f ...

execute the function whenever the variable undergoes a change

<script> function updateVariable(value){ document.getElementById("demo").innerHTML=value; } </script> Script to update variable on click <?php $numbers=array(0,1,2,3,4,5); $count=sizeof($numbers); echo'<div class="navbox"> ...

"Obtaining a MEAN response after performing an HTTP GET

I'm currently in the process of setting up a MEAN app, however I've hit a roadblock when it comes to extracting data from a webservice into my application. While returning a basic variable poses no issue, I am unsure how to retrieve the result fr ...

AngularJS offers a function known as DataSource for managing data sources

During a recent project, I had to convert xml data to json and parse it for my app. One issue I encountered was related to the DataSource.get() function callback in the controller. After converting the xml data using a service, I stored the converted data ...

"Unleashing the power of React Native: A single button that reveals three different names

I have a piece of code that changes the name of a button from (KEYWORD) to a different one (KEYNOS) each time it is clicked. How can I modify it to change to a third value (KEYCH), where the default name is (A, B, C... etc), the first click shows Numbers ...

Retrieve the selected option from the dropdown menu in the specified form

What should I do if I have numerous products and want users to be able to add new dropdown boxes dynamically? When the submit button is clicked, only the value of "category[]" within the form should be retrieved. https://i.stack.imgur.com/v1fnd.png Below ...

What is causing the malfunction in this code? (Regarding the key and value variable objects)

var elements = []; var attribute1 = $(index).attr('class'); //or any string var attribute2 = $(index).html(); //or any string elements.push({ attribute1: attribute2 }); When I run this code, the output I receive is: this Why am I unable to set ...

The functionality of Router.push() seems to vary depending on the timing

I'm attempting to utilize router.push() to modify the URL when the Search button is clicked. However, I've encountered a situation where this function only works sporadically. Ideally, after clicking the button, the user should be directed to the ...

Is there a built-in method called router.reload in vue-router?

Upon reviewing this pull request: The addition of a router.reload() method is proposed. This would enable reloading with the current path and triggering the data hook again. However, when attempting to execute the command below from a Vue component: th ...

CORS issue encountered by specific user visiting the hosted website

I recently developed a bot chatting website using Django and React, which I have hosted on HOSTINGER. The backend is being hosted using VPS. However, some users are able to see the full website while others encounter CORS errors where the APIs are not func ...

When utilizing JSON data in node.js, the .find() method may return undefined

I am currently working on a node server and my goal is to display JSON data when a specific ID is clicked. I have configured a dynamic URL that will retrieve the data of the clicked video using parameters and then compare it with the data in the JSON file ...

Start running additional JavaScript code only after the previous one has been fully executed

Scenario: I am facing a situation where I have a web form that is submitted through the following event listener: $('#myForm').on('valid', function (e) { ... } Within this function, I have a code snippet that fetches the geo location ...

Enhance Your HTML Skills: Amplifying Table Display with Images

Recently, I utilized HTML to design a table. The Table Facts : In the first row, I included an appealing image. The second row contains several pieces of content. In continuation, I added a third row. The contents in this row are extensive, resulting i ...

Javascript challenges for beginners in coding world

After running the code snippet, I encountered the following error messages: at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Fun ...

"Incorporating Node.js (crypto) to create a 32-byte SHA256 hash can prevent the occurrence of a bad key size error triggered by tweetnacl.js. Learn how to efficiently

Utilizing the crypto module within node.js, I am creating a SHA256 hash as shown below: const key = crypto.createHmac('sha256', data).digest('hex'); However, when passing this key to tweetnacl's secretbox, an error of bad key siz ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

Tips for attaching a callback to Angular UI Popover's trigger

I recently implemented an Angular UI Popover in the following manner: <div popover-is-open="prfList.isProfileClosed===false" popover-trigger="'outsideClick'" popover-append-to-body="true" popover-placement="right-top" popover-class="popover1 ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...