Converting an array of date strings to a single string in JavaScript

Here is the JSON format I received with dynamic data:

{"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]}

Now, I need to convert this into the following format:

range(20180723,20180723)

Below is my code snippet :

var data:Date[] = {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]}

  for(let i=0;i<=data.range.length;i++){
       console.log(data.range[i]);
       }

Answer №1

Let's tackle this challenge by interpreting your request.

If you want to convert a string date into a specific format, there are various ways to approach it. One of the simplest methods is to utilize libraries such as moment.js or date.js. With these libraries, you can input something like 2018-07-23T16:03:26.861Z and transform it into a Date object. Subsequently, you can extract necessary information from the date object, for instance;

const dateString = "2018-07-23T16:03:26.861Z";
let dateObject = moment(dateString, "YYY-MM-DDTHH:mm:ssZ").toDate();
let finalDateString = dateObject.getFullYear().toString()+dateObject.getMonth().toString()+dateObject.getDays().toString();

You can refer to the moment.js library documentation to learn more about achieving this conversion (docs).

An alternative method involves splitting the date string at the T character and removing any hyphens from the resulting array element to achieve the desired format;

const dateString = "2018-07-23T16:03:26.861Z";
const outputDateString = dateString.split("T")[0].replace(/-/g,"");

To delve deeper into how String.prototype.split() works, visit here, and for insights on String.prototype.replace(), check out this link.

Both methods mentioned above are effective and can be seamlessly integrated within your existing codebase using techniques like looping through data sets as shown below:

let data = {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]}

let output = "range("
for(let i=0;i<=data.range.length;i++){
   output += data.range[i].split("T")[0].replace(/-/g,"")+(i===0 ? "," : ")");
}
console.log(range) //"range(20180723,20180723)"

Answer №2

Here is a suggested solution:

var data = {"dates":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]};
for(var key in data){
  var result = '';
  var tempData = data[key].map(date => {
    var month = (new Date(date).getMonth()+1) <= 9? '0' + (new Date(date).getMonth()+1):''+(new Date(date).getMonth()+1);
    date = new Date(date).getFullYear().toString() + month + new Date(date).getDate();
    return date;
  });
  result = key + '(' + tempData.join(',') + ')';
  console.log(result);
}

Answer №3

To separate at T and discard the dashes from the initial segment is a potential strategy.

Answer №4

To extract the desired string, use

data.range[i].split("T")[0].replace(/-/g,'')

If you are looking for a similar solution, consider the following:

var data = {
  "range": ["2018-07-23T16:03:26.861Z", "2018-07-23T16:03:26.861Z"]
}

var result = [];// to store output
var strKey=Object.keys(data)[0];// key of the main object, i.e., range
var objData=data[strKey];// value of the key


for (let i = 0; i < objData.length; i++) {
     result.push(getFormattedDate(objData[i]));
}

var prepend=strKey+"("; // text to prepend
var postpend=")"; // text to append
result = prepend + result.join(",") + postpend;
console.log(result);


function getFormattedDate(date) {
    return date.split("T")[0].replace(/-/g,''); 
}

Answer №5

If you've thoroughly grasped the requirements, this brief code snippet should effortlessly handle your task in conjunction with your current code block. Simply split the datetime value by T and utilize the split() method, followed by replacing the - using replace()

var data = {"range":["2018-07-22T15:03:26.861Z","2018-07-23T16:03:26.861Z"]}
var expected =[];
for(var i=0;i<data.range.length;i++){
 expected.push(data.range[i].split('T')[0].replace(/-/g,""))
}
console.log('range('+ expected.join(',') +')

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

Analyzing file data while uploading the file

Does anyone have a solution for extracting the content from an uploaded file in express/nodejs without saving it as a temporary file? I have code that successfully pipes the input to a filestream, but I'm struggling to deserialize the upload to a pla ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...

Breaking down nested arrays in typescript

After receiving a response from the service, the data included the following: "rows": [ [ "stravi/aa", "202001", "59", "51", "2558.98", "0.5358894453719162", "1.9204668112983725", "140", "2.346630 ...

Transforming the hide/show functionality from JQuery to Vue

I created some hide/show panels using jQuery that I want to implement in Vue. However, when I try to integrate the jQuery functions into Vue, the functionality doesn't seem to work properly. The panels are not hiding/showing as expected. Does anyone ...

Is there a way to extract the current view date information from fullcalendar using Angular?

When working with HTML code... <full-calendar defaultView="dayGridMonth" [plugins]="calendarPlugins" #calendar></fullcalendar> I am wondering how to extract the date information from the #calendar element. I attempted to consult the fullcal ...

Is there a way to get a Chrome extension to run automatically in the background?

I am looking to develop a custom chrome extension with a countdown timer functionality that automatically runs in the background. However, I am facing an issue where my background.js file is unable to access the popup.html file. How can I execute scripts i ...

Performing an AJAX POST request in Laravel

I'm struggling with getting this ajax call to work, and I can't seem to figure out what's going wrong. View (html) <div class="col-sm-6 col-xs-3 pl0" style="margin-left: -5px;"> <button class="btn btn-primary visible-xs" n ...

Tips for maintaining consistent column width when scrolling down (column juggling) within a table in your Angular application

Take a look at this preview of the app I'm currently developing. https://stackblitz.com/edit/angular-ivy-3mrzkr In order to handle the large amount of data in my real app, I needed to incorporate a third-party scrolling module. After testing out cdk ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...

Receiving the result as well as encountering undefined initially during AJAX request

I have a dropdown menu, and when a user selects an option, an AJAX call is made to retrieve and display data based on the selected value. If the dropdown value is 2, it triggers the AJAX request. However, I am encountering two issues: https://i.sstatic.n ...

Retrieve a different action instance variable within the view

In the scenario where I have a View called home.html.erb and the corresponding controller shown below: class StaticController < ApplicationController def home @people = Person.all end def filter @people = .... end def contact end ...

Combining two ng-model inputs in Angular for seamless data integration

New to Angular and seeking some guidance. I currently have two input fields, one for the area code and the other for the number. // Input field for area code <input area-input type="tel" required="true" name="area" ng-model="employee.home.area">&l ...

Is it possible to modify the CSS of a single class when hovering over a child class of a different and unrelated class?

I am struggling with CSS combinators, especially when dealing with nested div, ul, and li elements. My issue involves changing the CSS of a div with the class "H" when hovering over li elements with the class "G". Since all of this is contained within a s ...

Is it possible for Typescript to automatically determine the exact sub-type of a tagged union by looking at a specific tag value?

I have an instance of type Foo, which contains a property bar: Bar. The structure of the Bar is as follows: type ABar = {name: 'A', aData: string}; type BBar = {name: 'B', bData: string}; type Bar = ABar | BBar; type BarName = Bar[&apos ...

Executing JavaScript in Rails after dynamically adding content through AJAX

Looking for advice on integrating JavaScript functions into a Rails app that are triggered on elements added to the page post-load via AJAX. I've encountered issues where if I include the code in create.js.erb, the event fires twice. However, removing ...

How come the behavior of Array.prototype.push() results in creating an endlessly nested array when used on itself?

While testing out the following code: const animals = ['pigs', 'goats', 'sheep']; animals.push(animals) console.log(animals); An error occurred in my testing environment: Issue: Maximum call stack size exceeded. What is c ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

Converting this HTML/PHP code into JavaScript: A step-by-step guide

I have been struggling to convert this code into JavaScript in order to set the document.getElementById().innerHTML and display it in HTML. Can anyone assist with writing this code in JavaScript? <form action='create_new_invoice.php?name="<?php ...

Transition from tslint to a new linter

Is it possible to remove tslint globally and switch to using eslint as the default in my Angular projects? When creating a new project with the command ng new myProj, I would like to have an eslint.json file instead of tslint.json. ...

Utilize JavaScript to connect WhatsApp with the website

I am looking to use Javascript to enable opening WhatsApp on both iOS and Android devices. Below is the code I have attempted: window.open("https://wa.me/15551234567"); window.open("https://api.whatsapp.com/send?phone=15551234567"); ...