Transform a datevalue obtained from an object into the format of DD-MM-YYYY

Is there a way to change the format of "20150812" to "12-08-2015"? Below is the date object that I am working with:

study response = [
{
    "dob": {
        "Value": [
            "20151208"
        ]
    }
} 
]

Javascript function

var dob = study["dob"]["Value"]; //returning 20151208

Expected output //08-12-2015

I've attempted the following: Date.parse(dob); //return NaN

Any assistance would be greatly appreciated.

Answer №1

I need to change the format of "20150812" to "12-08-2015"

Considering that dob is in text form and the desired result should also be a text string, the simplest way to achieve this is through text manipulation techniques like the following:

// var dob = study["dob"]["Value"]; //returning 20151208
var dob = "20151208";
var converted = dob.replace(/^(\d\d\d\d)(\d\d)(\d\d)$/, "$2-$3-$1");
console.log(converted);

This code will provide the expected output as specified.

Answer №2

To manipulate dates, you can utilize moment js library. For more information, check out: Moment.js
The following code snippet demonstrates how to convert a string date in the format YYYYDDMM to DD-MM-YYYY

<script src="https://momentjs.com/downloads/moment.min.js"></script>

<script>
   var mydate = 20151208;
   var str  = moment(20151208,"YYYYDDMM").format('DD-MM-YYYY');//This line is required
  console.log(str);
</script>

You can also extract day, month, and year using substrings

var str = "20151208";
var year = str.substr(0, 4);
var day = str.substr(4, 2);
var month= str.substr(6,2);
console.log( day+"-"+month+"-"+year);

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

Is there a way to manually add a function to the Javascript/Nodejs event queue?

Suppose I want to achieve the following: function doA(callback) { console.log("Do A") callback() } function doB() { console.log("Do B") } function doC() { console.log("Do C") } doA(doC) doB() I expect the output to be: Do A Do B Do C However ...

In search of a downloadable demo showcasing a .Net service that can be accessed using a purely JavaScript client, eliminating the need for IIS to host the service

Trying to figure out how to set up this configuration has been quite a challenge for me. I've heard it's possible, but finding clear instructions has proven difficult. While I'm attempting to navigate my way through this process, maybe stack ...

Guide on decoding a JSON string and saving the content as an array on an iPhone

When retrieving data from the server, a response containing a NSString with JSON data is received. The goal is to store this JSON data in an array. How can this be achieved? NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningRe ...

Develop a HTTP interceptor in the form of a class

I am currently grappling with the challenge of writing an angular http interceptor in plain TypeScript. The JavaScript code that I am attempting to convert is as follows: .config(['$httpProvider', function ($httpProvider) { var interceptor ...

Breaking AngularJS into an array

I need help splitting my data stored in a single array into multiple arrays. Currently, I am using "|" as the separator to split them, but I want to store each split value in separate arrays. https://i.sstatic.net/wW5QV.png JavaScript: { $ ...

"Did you come across `item()` as one of the methods within the array

While studying the book 'JavaScript and jQuery Interactive Front-End Web Development', I came across this interesting sentence: You can create an array using a different technique called an array constructor. This involves using the new keyword ...

Having trouble with jQuery's load() function not functioning as expected?

I am struggling with my jQuery ajax code. I have a div that should load content from a file when clicked, but nothing is happening. Can someone please review my script and help me identify the mistake? Here is my JavaScript code: $(document).ready(functi ...

Mastering the Art of Ajax with Codeigniter

I'm attempting to implement a simple AJAX feature on my CodeIgniter website. Below is the code in my view. Is there a way to debug from the controller? <div class="form-group"> <label for="name" class="col-sm-2 text-left">Full Name ...

React Native's state changes dynamically, however, the JSX conditional rendering fails to update the user interface accordingly

Greetings and thank you in advance for your time! I'm currently facing a unique challenge with React where I am struggling to render a specific UI element based on a check function. My goal is to create a multiple selection filter menu, where clickin ...

JavaScript Array Method Does Not Produce Array

I've been working on a function that should return an array of strings, but for some reason, it's not returning as expected: let returnArr = []; export async function snapshotToArray() { const db = firebase.firestore(); db.collecti ...

The process of integrating Tailwind elements into NextJs version 13

Can anyone help me integrate Tailwind elements into my NextJs project using JavaScript instead of TypeScript? I tried following the documentation, but the navbar component's expand button doesn't work. It seems like all components are having some ...

Nested UI routing with hidden display

I am working on a website using AngularJS and Ui-router. Index.html <body> <a href="#">Home Page</a> <div ui-view></div> </body> Javascript: .config(function($stateProvider, $urlRouterProvider) { $statePro ...

What is the process of emphasizing a WebElement in WebdriverIO?

Is there a way to highlight web elements that need to be interacted with or asserted in webdriverIO? Or is there a JavaScript code similar to the javascript executor in Selenium that can be used for this purpose? ...

Validation of a multi-step form ensures that each step is filled out

I'm completely new to Angular and I'm attempting to implement validation in my form. The form structure was not created by me and is as follows: <div> <div ng-switch="step"> <div ng-switch-when="1"> < ...

Odd replication occurring while storing object attributes in an array

JSFiddle I am trying to iterate through an object, make changes to each property, and then add them to an array. Each property is added multiple times (in the JSFiddle example, I have set it to be added twice for simplicity). Each iteration should have so ...

Trouble encountered when implementing setInterval in Next.js

While working on a progress bar component in Next.js and tailwind.css, I used JavaScript's setInterval() function for animation. Below is the code snippet: import React, { useState } from "react"; const ProgressBar = () => { let [progress, setPr ...

Modify the row's background color after clicking the delete button with jquery

Greetings, I am facing an issue with changing the color of a row in a table when clicking on a delete button. Despite trying various methods, I have not been successful. How can I modify the ConfirmBox() method to change the row's color? Your assistan ...

Deciphering MP3 files in VB.net using JSON byte array

It's a bit of an unusual situation I've got here! I have several Android devices running custom delivery tracking software (which I developed). One of the features allows users to record a voice report and send it via mobile networks. Everything ...

Can one jQuery script be used for multiple ajax 'like' buttons?

Hey there! I'm working on an Ajax 'like' button that utilizes jQuery. This button will be utilized multiple times on a single page. I'm looking for a way to streamline the process and avoid including the jQuery script multiple times. Is ...

Which operator is best suited for working with JSON data?

file = open(file_path, "rb") file_data = json.load(file) MANIPULATE THE DATA HERE print(file_data) json.dump(file_data, file) I keep getting errors when saving or opening the JSON file. The file is a dictionary where I modi ...