Converting a string to a date in Vue.js

My API is returning a date string in the format: DD_MM_YYYY_hh_mm__ss

I am aiming to present the string in the format: DD/MM/YYYY hh:mm:ss

What is the best method to achieve this?

Answer №1

To transform the underscore sequences into the appropriate characters, you can utilize their positions within the input string:

function updateDate(date) {
    return date.replace(/_+/g, (_, n) => (n < 10) ? "/" : (n > 10) ? ":" : " ");
}

console.log(updateDate("DD_MM_YYYY_hh_mm__ss"));

Alternatively, a slightly simpler approach can be taken:

function updateDate(date) {
    let n = 0; return date.replace(/_+/g, () => "// ::"[n++]);
}

console.log(updateDate("DD_MM_YYYY_hh_mm__ss"));

Answer №2

A method to achieve this is:

const str = '18_03_2022_12_21_34'
// Convert to string
const res = str.split('_')
const r = res.slice(0, 3).join('/') + ' ' + res.slice(-3).join(':')
console.log(r)
// Alternatively, convert to date
console.log(new Date(res.slice(0, 3).join('/').split('/').reverse().join('/') + ' ' + res.slice(-3).join(':')))

Answer №3

Vue String Date Time Filter

Implementation:

Vue.filter('convertStringToDateTime', function ( dateTimeString ) {
    if (!dateTimeString) return ''
    return dateTimeString.replace(/_+/g, (_, n) => (n < 10) ? "/" : (n > 10) ? ":" : " ");
})

Example:

{{ 12_04_2021_12_59_34 | convertStringToDateTime }}

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

Occasionally, the view fails to update following an $http request

Although this question has been posed multiple times before, none of the solutions seem to be effective for my issue. Controller app.controller('HomeController', function ($scope, $timeout, $http) { $scope.eventData = { heading: ...

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 ...

Obtain the content of every cell in a constantly updating table

I have created a dynamic table as shown below: <table id="sort" class="table"> <thead> <tr> <th>Column Name from DB*</th> <th>Record Le ...

What is the best way to keep my data within a global variable?

$(function(){ let spaceTravelersData; $.getJSON('http://api.open-notify.org/astros.json', retrieveData); function retrieveData(data) { spaceTravelersData = data; } alert(spaceTravelersData.people[0].name) }); I a ...

Retrieve an HTML document from a specified URL using JavaScript AJAX methods

var $ = require('jquery'); $.ajax({ type:"GET", dataType: 'html', url: 'http://www.google.com/', success: function(res){ console.log(res); } }); The error displaying in the console is: XMLHttpRequest cannot lo ...

Unable to locate an element on the webpage due to a JavaScript-based error, which then becomes hidden after a few seconds. (Registration form)

While completing a registration form, I encounter a hidden message after clicking on the register button. Struggling to locate this elusive element has been an ongoing challenge for me. Unfortunately, my attempts to find the element have been unsuccessful ...

What could be causing the if statement to evaluate as false even though the div's style.display is set to 'block'?

Building a react application using createreactapp and encountering an issue with an if statement that checks the CSS display property of a div identified as step1: const step1 = document.getElementById("step-1") if (step1.style.display === 'blo ...

JavaScript encountered an issue: Uncaught ReferenceError - 'userNumber' is undefined at line 43

I'm currently working on a JavaScript guessing game where I've already set up the necessary functions. However, I keep encountering an error. An error in my JavaScript code is causing a ReferenceError: userNumber is not defined on line 43 to b ...

Securing a fixed path in Express and Nodejs: Best practices

Using the latest versions of Node and Express, I have organized my project into two folders: public and secured. I want to restrict access to the secured folder to only authenticated users. I have implemented a custom login system, but now I am unsure of ...

serve.js module located within the node_modules directory

I recently stumbled upon this snippet in the package.json file: "serve": "node ./node_modules/serve/bin/serve.js -p 5050" After exploring that directory, I discovered the presence of the serve.js file, which appears to be utilized for hosting and serving ...

Automatically restarting Vue when utilizing fs.writeFile within socket.io

Whenever a client uploads an image, they should use the following code to emit it: var image= { imageData: {base64:dataurl}, } socket.emit("Toserver", image) In Vue, there is always a restart when running npm run dev. On the server side: socket.on(&a ...

Using the Mongoose $or operator with a nested array in query conditions

Here are the schemas I am using: //ProjectModel const ProjectSchema: Schema = new Schema( owner: { type: Schema.Types.ObjectId, ref: "User" }, users: [{type: Schema.Types.ObjectId, ref: "ProjectUser", unique: true }] ); //Project Use ...

The querySelector function is now encountering errors due to a change in the data

Currently, I am utilizing a query selector to retrieve an input when a user selects different buttons. Initially, the buttons had options such as: 8x10 inch 12x16 inch 20x24 inch However, I made changes to the options format like so: 8" x 10" ...

What is the process for changing the output paper size to A4 in React Native (expo android)?

Using React Native to develop an Android app for billing purposes, I encountered an issue with the output paper size being 216mmX279mm instead of the standard PDF size of 210mmX297mm. Utilizing expo-print and printToFileAsync from expo, I aim to achieve a ...

Where is the location of the directory on the hard drive that was created using the getDirectory() method in HTML5?

I have been working on creating, deleting, and reading directories but I am unsure of where they are located on the hard drive. fs.root.getDirectory('something', {create: true}, function(dirEntry) { alert('Congratulations! You have succes ...

Problem encountered when displaying a modal with Vue.js

I'm encountering an issue with displaying a bootstrap modal using vue.js and laravel 5.3. I have included the vue model inside a blade.php file, but the modal doesn't seem to be working correctly. Here is an example of the code: html: <div i ...

Support for h264 in Windows Media Player across various versions of Windows operating system

Are there specific versions of Windows that are capable of playing h264 videos with Windows Media Player installed by default? Is it feasible to determine this support using Javascript? We currently deliver MPEG-4 video files through Flash, but some users ...

Guide on aligning a popup next to the button that activated it using CSS and JavaScript

I am currently generating a dynamic quantity of divs, each containing a button that triggers a popup when clicked. I am attempting to position the popup below the specific button that activated it, but it remains static and does not move accordingly. <d ...

Is there a way to retrieve student data by searching for a specific field?

I have a search button on the front end that allows users to input a student number and retrieve the corresponding information from my schema... Currently, I am mapping the data for all products However, when attempting to log the data, I am getting a nu ...

obtain a Javascript variable within a Jade template by using inline code

script. var hide_section = 'block'; .title(style='display:#{hide_section}') I received an undefined value, any thoughts on why? Could it be because #{hide_section} is trying to access a variable from the back-end, such as the cont ...