Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows:

{
    "_id" : "xxxxxxxxxxxxxxx",
    "SchoolId" : 1,
    "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"),
    "PersonDetails" : [ 
        {
            "Name" : "John",
            "AddressZone" : 6,
        }, 
        {
            "Name" : "Mary",
            "AddressZone" : 5,
        },
    ],
    "CreationTimestamp" : ISODate("2015-11-10T10:55:00.009Z")
}

My javascript file is structured like so:

var printData = function(doc){
        print(doc.CreationTimestamp+","+doc.SchoolId+","+doc.PersonDetails.Name+","+doc.PersonDetails.AddressZone)
    };

var cur = 
    db.test.aggregate([
        {$match: {_id: "xxxxxxxxxxxxxxx"}},
        {$unwind: '$PersonDetails'}]);

cur.forEach(printData);

When I execute this command:

.\mongo localhost/test test.js > output.txt

The resulting output (only showing a sample) is:

Tue Sep 22 2015 14:01:58 GMT+0100 (GMT Daylight Time),1,John,6

However, I want the date to be displayed in the format of:

22/09/2015 14:01:58

Is there a method or solution to format the datetime as indicated above?

Answer №1

If you want to work with the date in JavaScript, you can easily do so by creating a new Date object:

var currentDate = new Date(document.CreationTimestamp);

Once you have the date object, you can manipulate it as needed. Here is an example of formatting the date:

var formattedDate = currentDate.getDate() + '/' + (currentDate.getMonth() + 1) + '/' + currentDate.getFullYear() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes() + ':' + currentDate.getSeconds();

To explore more functions that can be called on a date object, visit http://www.w3schools.com/jsref/jsref_obj_date.asp.

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

Generating a JavaScript array using concealed data

var a1=$("#orderprogress").val().toFixed(2);//a1=50 var a2=$("#poprogress").val().toFixed(2); //a2=70 If I were to create an array in this format, how should I proceed? graphData = new Array( [a1 value,'#222222'],//[50,'#22222 ...

Unable to locate 'react' for mdl module

Currently working on my first website using react, following a tutorial available at this link I am attempting to install and utilize the material lite module, but encounter a compilation error when starting npm with the following message: Error: Module ...

What is the best way to modify an Li element using the DOM in JavaScript?

Just the other day, I discovered how to use JavaScript and DOM to add and delete Li elements. Now I'm curious about how to edit those Li elements using DOM. Any suggestions? Thank you! ...

Transfer data via ajax to the controller

I need assistance with storing a file in my database using Tabulator without having a form already created. I am currently creating a simple input element like this: var editor = document.createElement("input");. After clicking the file, it trigg ...

Guide to smoothly scroll to the top of an element containing collapsible panels using Jquery

I've encountered an issue with a series of divs that are set to toggle the state of a collapsible div upon clicking (similar to an accordion widget). The functionality works as intended, but I'm facing a challenge - I want the page to scroll to t ...

Update the Vue method

Is there a way to optimize the following method or provide any suggestions on what can be improved? I am trying to create a function that converts author names from uppercase to only the first letter capitalized, while excluding certain words ('de&apo ...

Sending a blob through AJAX to a different domain using CORS

Could someone please explain why my current request is being blocked by the SO policy restriction? Javascript Code: var blob = new Blob([req.response], {type: "application/octet-stream"}); req = new XMLHttpRequest(); req.open("POST", ws_path(other_contex ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Utilizing JavaScript within my WordPress site

I'm experiencing some issues with my JavaScript code in WordPress. I have been trying to use the following code on my page, but it doesn't seem to work properly. Can someone please guide me on how to integrate this code within my WordPress page? ...

Console command to change paragraph tag color---Modifying the color

I am attempting to change the color of all paragraph tags on a webpage to white by utilizing the console. My initial attempt was: document.p.style.color = 'white'; However, this method did not have the desired effect. Interestingly, I have had s ...

Utilize identical animations across various elements

I have a canvas animation in JavaScript that is currently limited to one canvas element with the id "stars". I want to be able to use this animation multiple times without repeating the code. Is there a way to add a class for the canvas elements instead of ...

Internal server error frequently occurs when there is an issue with Ajax requests in a Laravel application

Greetings, fellow developers! I am encountering an issue with the comments system in Laravel and Ajax. While it functions correctly with PHP alone, I am facing difficulties when using Ajax. The error message I am receiving is as follows: Status Code:50 ...

Completion of TypeScript code is not working as expected, the variable that is dependent upon is not

Looking for assistance with creating code completion in TypeScript. Variable.Append1 Variable.Append2 Variable.Append3 I have defined the following class: class Variable { Append1(name: string){ if (name == undefined) ...

JSPM encountered an issue with installation from GitHub (404 error), but it is able to successfully install packages from npm

I am encountering a frustrating issue with my Package.json file for a GitHub repository in my organization. Attempting to pull it in via jspm is causing errors. { "name": "tf-modernizr", "version": "1.0.0", "description": "", "main": "modernizr.js ...

Obtaining information from a intricate string input

{JSON.stringify(walletData.transactions, null, 2)} My goal is to extract backend data and display it as a table. The response has been converted into an array as shown below. [ { "date": "Nov 07, 2023", "description" ...

"Unsuccessful jSON request made by Ajax resulting in undefined response

I've implemented an ajax call to fetch data from a json file and display it in an HTML table. Everything was working fine initially, but now it seems to be returning UNDEFINED. Could it be that the data from the json file hasn't finished loading ...

When using v-select to search for items, the selected items mysteriously vanish from

I recently worked on a project where I encountered a similar situation to the one showcased in this CodePen. Here is the link to the specific CodePen One issue I faced was that the selected items would disappear when performing an invalid search. After i ...

German-formatted jQuery datepicker

Need help in changing jQuery datepicker formatting from MM/DD/YYYY to German style as d MMMM yyyy. Tried implementing the following code but encountering issues. <script type="text/javascript"> $(function () { $('.datepicker&ap ...

Replace !important with JavaScript/jQuery when using animate()

I need to animate the background-position-x, but there is a background-position: 0 0 !important; set in the css that cannot be removed. Is it possible to work around this using JavaScript? My jQuery code is functioning as intended, but it is being overridd ...

Error: Cannot access the 'top' property of an undefined object

Here is a snippet of my jQuery code: $(document).ready(function(){ $('.content-nav a').on('click',function(){ var str = $(this).attr("href"); var the_id = str.substr(1); $("#container").animate({ scrollTop: $ ...