Adding a zero before the month in Vue JS with the use of the Date object

Hey there, I'm facing an issue with one of my functions that displays the date. Currently, it shows up like this: 5/31/2021. However, I would like it to appear in the format 05/31/2021. Below is the code snippet for reference:

<span>{{ dtFormatter(course.updated_at) }}</span>

dtFormatter(d) {
  var dateObj = new Date(d);
  var day = dateObj.getUTCDate();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var year = dateObj.getUTCFullYear();
  return day + "." + month + "." + year;
},

Answer №1

If necessary, you can utilize the padStart method to include a leading Zero:

day.padStart(2, '0') + '.' + month.padStart(2, '0') + '.' + year

Ensure that both day and month are strings.

Answer №2

You have already determined the day, which means you are ready to proceed.

`0${day}`.slice(-2)

As a result, you will see numbers ranging from 01 to 09 and 10 to 31.

Answer №3

To ensure that there is a leading zero, you can utilize the String#slice method:

('0' + day).slice(-2) + '.' + ('0' + month).slice(-2) + '.' + year;

Please keep in mind that padStart may not be compatible with Internet Explorer.

Answer №4

In a response from @HassanImam, it was suggested to use this concise one-liner code:

new Date().toLocaleDateString('en-UK')

Alternatively, you can achieve the same result using the following code snippet:

const date = new Date()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
const y = String(date.getFullYear())

const formattedDate = [m, d, y].join('/')

console.log(formattedDate)

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

Creating a dynamic dropdown menu that changes based on the selection from another dropdown menu

I'm working on a project that requires users to make specific selections in dropdown menus that are interconnected. Does anyone know how to set up a form so that the options in dropdown menu #2 change based on what the user selects in dropdown menu #1 ...

Enhancing connections in a MongoDB database

Can someone assist me with implementing the update function in the assignmentsController? I want users to create an assignment and then be able to add a quiz to it. After updating the assignment quiz section, here is an example of what I expect as a return ...

Implementing Ajax calls to dynamically update Datatable results

Currently integrating Datatables.js with an ajax call for data retrieval. The json response I'm receiving is as follows: "success":true,"message":"","items":[{"id":"1","ip_address":"127.0.0.1","email... My data is stored within the data.items array ...

Merging two regular expressions for AngularJS form fields

How can I combine these two regex patterns for an AngularJS form field? \d{4}([- ]*)\d{6,7} OR [a-zA-Z0-9]{4,12} I attempted to do this like so: <input type="text" pattern="\d{4}([- ]*)\d{6,7} | [a-zA-Z0-9]{4,12}" class="form- ...

Design a button in d3.js that toggles the visibility of a rectangle and text

Looking to use d3.js to create a simple list from data in a box, complete with a button to toggle the visibility of the box and its content. Ran into two errors during implementation: 1) The list is starting at item 2 for some reason - where's the fi ...

Utilize the identical promise within the `Then` block

I am curious to know whether it is possible to call the same promise twice in the following manner: //receiver is sent if the mail should be sent to someone else and will have a //different email body const body = (req.body.receiver) === undefined ? &ap ...

What is the best way to pass data between sibling components using services?

I'm looking to connect a service to a component that can fetch data, share objects, and communicate with other components that are already linked to the database. I've established a service named DashService as follows: import { Injectable } fro ...

Objects beyond a distance of 1 unit start to vanish when employing ArrayCamera

After implementing an ArrayCamera to wrap my PerspectiveCamera, I noticed that objects located more than 1 unit away from the origin point (0,0,0) appear to vanish in the render. var camera = new THREE.PerspectiveCamera(); camera.viewport = new THREE.Vecto ...

Highcharts feature enhancement: Adjusting zIndex of legendItem on mouseover/mouseout

I have a chart that includes a 'total' sum value series alongside other values. My goal is to initially hide or place this 'total' column behind the others, and then bring it to the front when the series' legendItem is hovered ove ...

Element eradicated by mysterious force - what is the reason behind this destruction?

I encountered a peculiar issue while working on a JS game demo. For some reason, one of the functions is unexpectedly deleting the container element (even though I didn't intend for it to do so). This function usually creates another element inside th ...

Passing the unique identifier of a record in NextJS to a function that triggers a modal display

I'm currently facing an issue with my NextJS component that displays a list of people. I have implemented a delete button which triggers a modal to confirm the deletion of a person, but I am struggling with passing the id of the person to be deleted. ...

JavaScript file slicing leads to generating an empty blob

I am currently working on a web-based chunked file uploader. The file is opened using the <input type="file" id="fileSelector" /> element, and the following simplified code snippet is used: $('#fileSelector').on('change', functio ...

Creating a Dual Y-Axis Chart with Two Sets of Data in chart.js

I utilized the chart.js library to write the following code snippet that generated the output shown below. My primary concern is how to effectively manage the labels on the horizontal axis in this scenario. CODE <!DOCTYPE html> <html lang="en"& ...

Error: An uncaught exception occurred when trying to access a seekable HTML5 audio element, resulting in an IndexSize

While trying to utilize the HTML5 API along with SoundManager2, I encountered an issue. My goal was to determine the duration of a song in order to create a progress bar that would update as the song played. However, every time I attempted to retrieve the ...

Combining Strings and Integers in Javascript

Currently, I am facing a frustrating syntax issue with my code. I am using Scissors, a Node Module for managing pdf files. The documentation describes the syntax for selecting specific pages of the Pdf: var scissors = require('scissors'); var p ...

Utilize Protractor to extract the text within a specified span element

Is it possible to check if the text of the span within the button is "Vigente" using expect and Jasmine? If so, how can I achieve this? <button _ngcontent-hke-28="" class="btn btn-success disabled" tabindex="-1"> <span _ngcontent-hke-28="" class= ...

Is there a way to transfer textbox value to ng-repeat in AngularJS?

1) The Industry dropdown menu corresponds with a code textbox. Depending on the selected industry, the code will change accordingly. 2) There is a dynamic feature to add or delete Movie Names and Directors' names. In this table, there are three colu ...

I am looking to display data in Angular based on their corresponding ids

I am facing a scenario where I have two APIs with data containing similar ids but different values. The structure of the data is as follows: nights = { yearNo: 2014, monthNo: 7, countryId: 6162, countryNameGe: "რუსეთის ...

There was a problem with the ES Module requirement while trying to use retry-axios, resulting in the following error: [

const rax = require('retry-axios'); Error [ERR_REQUIRE_ESM]: encountered an issue with require() for ES Module While attempting to set up a retry mechanism using retry-axios, I ran into the Error [ERR_REQUIRE_ESM]: require() of ES Module error. ...

Load gallery thumbnails dynamically using JavaScript or jQuery

Currently, I have implemented TN3 gallery in a WordPress website (not as a plugin, but as a jQuery library). While the large images in the gallery load dynamically and do not affect the page load, the thumbnails are all loaded at once, even if they are no ...