Utilize the function with another function (difficult to articulate)

Apologies in advance for my beginner question.

Review the code snippet below:

var dt = new Date(t*1000);
var m = "0" + dt.getMinutes();

Depending on the t variable (unix time), the output can be one of the following:

m = 054 // 54 minutes
m = 03 // 3 minutes

The formatting breaks when there are too many minutes. To solve this, we need to extract only the last two characters by using:

var m = "0" + dt.getMinutes();
m = m.substr(-2);

Resulting in:

m = 54 // 54 minutes
m = 3  // 03 minutes

Problem solved, right? However, repeating the variable assignment seems inefficient. I attempted:

var m = "0" + dt.getMinutes().substr(-2);

But encountered this error:

TypeError: dt.getMinutes(...).substr is not a function

Is there a more concise way to achieve this?

Answer №1

Date Manipulation Guide explains that Date.getMinutes returns an integer, not a string. Therefore, attempting to use substr on it will result in an error. However, wrapping the "0" + dt.getMinutes() expression in parentheses converts it to a string, allowing you to successfully call substr:

var dt = new Date();
var m = ("0" + dt.getMinutes()).substr(-2);
console.log(m);

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

Making AJAX requests repeatedly within a loop

My current challenge involves implementing multiple ajax requests within a loop to populate several dropdown lists. Running the requests sequentially has resulted in only the last item in the loop being populated with values. var targetcontrols = []; ...

Steer clear of chaining multiple subscriptions in RXJS to improve code

I have some code that I am trying to optimize: someService.subscribeToChanges().subscribe(value => { const newValue = someArray.find(val => val.id === value.id) if (newValue) { if (value.status === 'someStatus') { ...

Ways to make a button blink using AngularJS

Currently working on an AngularJS SPA application where a button is present in the front-end HTML page. When this button is clicked, it triggers an operation which takes some time to complete. I want to inform the user that the operation is still in prog ...

Display the element only when the request sent with getJSON exceeds a certain threshold of time in milliseconds

Here's a snippet of my JavaScript code: surveyBusy.show(); $.getJSON(apiUrl + '/' + id) .done(function (data) { ... surveyBusy.hide(); }) .fail(function (jqXHR, textStatus, err) { ... surveyBusy. ...

Ways to retrieve a JSON element and incorporate it into a CSS styling

Can someone assist me in converting a JSON object for use in CSS? I've attempted to do this using Vue.js, creating a map legend with v-for to generate the legend. However, if there is an alternative method that allows me to take a JSON object and ins ...

Incorporating a jQuery word count and limit within PHP code: a step-by-step guide

I am encountering an issue with a textarea count code. It functions perfectly on its own but when I integrate it as shown below, it stops working without throwing any errors. I have been trying to resolve this for more than 3 days now. Any assistance would ...

Changing the text color in a React Native TouchableHighlight component

How does TouchableHighlight change the text color when tapped? I have already configured the backgroundColor using underLayColor. Here is my updated code snippet: <TouchableHighlight style={{ borderRadius: 5}} ...

Is this method an effective way to create global states across React components?

After delving deep into props-drilling while coding a full-fledged web application with React, I've decided to explore using React 'contexts'. Following the guidelines in the React documentation, I am implementing an approach to make my stat ...

Concerns have been raised regarding the lack of light and shadows being detected by THREE.BufferGeometry in JavaScript/th

I've been trying to generate terrain using noise functions, but I'm running into an issue where the BufferGeometry mesh isn't receiving any light from PointLight. When I switch to AmbientLight, the BufferGeometry is visible, but not with Poi ...

Stop the duplication of the HTML content to ensure only one copy is saved

Recently, I have been coding a feature that saves the HTML of the currently displayed page to another file upon pressing a button. However, I encountered an issue where if the button is pressed multiple times quickly, the saved file contains incorrect HTML ...

Troubleshooting the issue with the default dropdown select in AngularJS

var jsonData ='[ {"type":"product", "id":1,"label":"Color", "placeholder":"Select Jean Color", "description":"", "defaultValue":"Brown", "choices":[{ "text":"Denim", "price":"$0.00", "isSel ...

Exploring the power of ElasticSearch alongside Mysql

As I plan the development of my next app, I am faced with the decision between using NoSQL or a Relational Database. This app will be built using ReactJS and ExpressJS. The data structure includes relational elements like videos with tags and users who li ...

Best practices for assigning values to model field in EXT JS are as follows:

I'm facing an issue with a certain model structure: Ext.define('my.workspace.Area', { extend: 'Ext.data.Model', idProperty: 'id', fields: [ {name: 'id', type: 'string'}, {n ...

HTML5Up! Skyrocketing with Meteor showers

While attempting to utilize a responsive site template from , I encountered several issues. To test the template, I downloaded the Striped package and created a clients folder in a Meteorite app where I placed the Striped folder. In order to make it work, ...

The initial value for React input is vacant and is not capturing either the state or the prop value

After utilizing Vue for an extended period, I have now transitioned to React. To practice, I am attempting to convert some basic Vue components into React. My initial Vue code was simple as shown below: <template> <div> <h1>Hello { ...

Resolving Typescript custom path problem: module missing

While working on my TypeScript project with Express.js, I decided to customize the paths in my express tsconfig.json file. I followed this setup: https://i.stack.imgur.com/zhRpk.png Next, I proceeded to import my files using absolute custom paths without ...

Is there a way for me to divide the data in a JSON file and display user tags in place of their IDs?

Looking to create a list admins command for a bot, I'm facing challenges in converting user ids to tags within the command. Take a look at what I have accomplished so far: const { MessageEmbed } = require('discord.js'); const { readFileSync, ...

Incorporating Material-UI with React Searchkit for a seamless user experience, featuring

I encountered an issue when trying to use both searchkit and material-ui in my React application. The problem arises from the fact that these two libraries require different versions of reactjs. Initially, everything was working fine with just searchkit in ...

Tips on choosing and retrieving the value of filled text area fields using jQuery

I am struggling with selecting non-empty textareas and retrieving their values using jQuery. Here is a snippet of my code: <div class="item"> <textarea class="col-sm-10 comment">TextArea1</textarea> </div> <d ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...