Can you suggest a simpler approach to implementing this function?

Greetings to all who are perusing this message.

I have devised a technique for retrieving today's date along with the current time. If the deadline value in the database is null, it will fetch the current datetime and format it correctly. Otherwise, it will simply format the deadline.

However, I am curious if there exists a simpler way to accomplish this?

getFormattedDateTime(deadline){
      var formattedDateTime;

      if(deadline == null){
          var currentDate = new Date();
          var month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
          var day = ('0' + currentDate.getDate()).slice(-2);
          var year = currentDate.getFullYear();
          var hour = ('0' + currentDate.getHours()).slice(-2);
          var minute = ('0' + currentDate.getMinutes()).slice(-2);
          var formattedDate = year + '-' + month + '-' + day + 'T' + hour + ':' + minute;

          formattedDateTime = moment(formattedDate, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
      } else {
          formattedDateTime = moment(deadline, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
      };

      return formattedDateTime;
  }

Answer №1

In agreement with @Andrew, it appears that you are already utilizing moment

This updated version will replicate the behavior of your current function

function adjustDateTime(limit){

      if(limit == null){
          limit = moment().format('YYYY-MM-DD HH:mm'); 
      }

       return moment(limit, 'YYYY-MM-DD HH:mm').format('YYYY-MM-DDTHH:mm');
  }

Answer №2

For those utilizing momentjs, simply passing a Date object to the moment function will suffice. If no arguments are provided, it will default to the current time (similar to new Date()).

formatDateTime(dueDate) {
    return moment(dueDate).format('YYYY-MM-DDTHH:mm');
}

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

Unable to successfully link filter outcomes with input in AngularJS

Here is the code snippet I am working with: <body ng-app=""> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {nam ...

What is the right way to utilize props in Vue?

I have a question that my colleague and I are debating. He believes in accessing props in a component using this.$props[propName], while I think it should simply be accessed via this[propName]. I couldn't find any mention of using $props in Vue docume ...

Verify if the input field is devoid of any content or not

I am planning to create a validation form using Vanilla JavaScript. However, I have encountered an issue. Specifically, I want to validate the 'entername' field first. If the user does not enter any letters in it, I would like to display the mess ...

``Can you provide guidance on excluding matching values from a dictionary object in a Angular project?

I've developed a function that takes a dictionary object and matches an array as shown below: const dict = { CheckAStatus: "PASS", CheckAHeading: "", CheckADetail: "", CheckBStatus: "FAIL", CheckBHeading: "Heading1", CheckCStatus: "FAIL", ...

Using ThreeJs to create interactive 3D objects with button-controlled movement

Currently, I'm diving into the world of Three.js and I have a fascinating project in mind. I want to create movement buttons that will control the position of a sphere object. Through some research, I found out that I can use the onclick function on b ...

Troubleshoot React component re-rendering issue

I'm currently facing a challenging bug that only occurs very sporadically (about once every few dozen attempts). During the render call, I'm determined to gather as much information as possible: I want to understand what triggered the rerender ...

Implementing precise search functionality in a table with jquery datatables

Hey there, I'm attempting to implement an exact search feature in jQuery datatables. In my table, I have a column called "status" with values of either "paid" or "unpaid". Currently, when I type "unpaid", it correctly displays only the unpaid record ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

"Users have reported that the Express body-parser feature sometimes results in req.body returning

I have developed a basic Express server that utilizes the body-parser module to access POST parameters. Here is how my application is structured: /index.js: 'use strict'; const express = require('express'); const app = express(); con ...

Problem encountered with @HostListener

In an Angular component, I have the following code snippet that is functioning as intended: @HostListener('document:click', ['$event']) onClick(event) { if(!this.eRef.nativeElement.contains(event.target)) { console.log("clicked out ...

What is the button that switches the bootstrap modal?

With my bootstrap modal form, I have multiple buttons that trigger it as shown below: <a href="javascript:void(0)" data-toggle="modal" data-target="#specialoffer"> <button class="green full" id="button1">Ask Question</button> </a& ...

Tips for generating a <div> element with multiple children using a loop

section, I have configured a div element with a class named div class = "postWindow". When it comes to the HTML code, here is an example: <div class = "postWindow"> <div class = "userName">Initial Name</div> <div class = "p ...

Steps to arrange by the number of rows in ag grid

I've been experimenting with the rows group feature in ag-grid, But I'm curious if it's feasible to sort the group column based on the number of rows within each group? Here is an example of what I am trying to achieve: https://i.sstatic. ...

Having trouble replicating the progressive response from the server in node.js

Hey there, I recently dipped my toes into the world of node.js and decided to give it a shot. Following Ryan Dahl's tutorial (http://www.youtube.com/watch?v=jo_B4LTHi3I) as my starting point, I reached a section around 0:17:00 where he explains how s ...

Incorporate style elements dynamically using an array in Vue

My progress bar's width and color are determined by data from an array. The color of the bar changes based on the value of the data - grey if the progress is 0, blue if it's more than 0, and green if it's 100. <div class="card-item" v-fo ...

"Utilize Ajax to trigger a custom alert message once data is loaded and ready

Is it possible to customize the data object in order to show a JavaScript alert saying "The email address has already been registered!"? Currently, the servlet returns a boolean indicating whether the email is already in the database. $('#emailInput ...

tips for enabling communication between the server and client

As someone who is new to the world of web development, please bear with me as I ask a question out of curiosity. I am wondering if there is a method for the server to push messages to clients. For instance, imagine a client's webpage featuring a news ...

Using Vue to Retrieve Values from a Django Dictionary

When using Vue, the expression {{ game.data }} will return the following data: [ { "game": 1, "turn": 1, "player": 1, "word": "trend", "score": 18 }, { "game": 1, "turn": 2, & ...

The IE9 confirmation dialog fails to pause for user response, resulting in automatic postback before user input is received

Behind the Scenes btnNext.Attributes.Add("onclick", " return Verification(this,'" + GetLocalResourceObject("message").ToString() + "'); ") .ASPX Page [Within javascript tags] function Verification(source, message) { var dialog = '< ...

Sending a sound recording to the express js server with the help of multer

I'm currently working on a project where I need to record audio and save it in my local directory (uploads folder) using express js and multer. The recording part is working fine with mic-recorder-to-mp3, but I'm facing an issue with saving the r ...