What is the process for transforming MongoDB timestamps into a readable date format?

My createdAt property is structured as follows: 2020-03-30T12:44:20.221+00:00. I am looking to convert it to something similar to 30 march 2020, excluding the time and timezone information. Is there a way to achieve this? Thank you.

Answer №1

To work with dates in JavaScript, you can utilize the Date constructor:

var createdAt = "2020-03-30T12:44:20.221+00:00"
var date = new Date(createdAt)
console.log(date.getDate() +  " " + date.toLocaleString('default', { month: 'long' }) + " " + date.getFullYear())

// Another shorter way to achieve the same result (Credit to @RobG)
console.log(date.toLocaleString('en-GB', {day:'numeric', month: 'long', year:'numeric'}))

Answer №2

When you mention that you only need the date and not the time and timezone, it's important to consider that a timestamp like 2020-03-30T12:44:20.221+00:00 essentially represents UTC due to its zero offset. However, depending on the specific time in the timestamp and the offset of the host timezone, using methods that are not based on UTC might result in a date that is off by one day compared to the UTC date if it falls within the local timezone offset close to midnight.

For example:

let formatLocal = new Intl.DateTimeFormat('en-GB', {year: 'numeric', month:'long', day:'2-digit'});
let formatUTC   = new Intl.DateTimeFormat('en-GB', {year: 'numeric', month:'long', day:'2-digit', timeZone:'UTC'});

// Timestamps
['2020-03-30T12:44:20.221+00:00', // from OP
 '2020-03-30T00:04:00.000+00:00', // Just after midnight UTC
 '2020-03-29T23:54:00.000+00:00'  // Just before midnight UTC
].forEach(s => {
  let d = new Date(s);
  console.log(
   `${s}\nLocal: ${formatLocal.format(d)}\nUTC  : ${formatUTC.format(d)}`
  );
});

In the scenarios of the second or third examples mentioned above, the local date should differ by a day from the UTC date.

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

Encountering difficulties in linking socket.io node server to react frontend. Receiving a "404 (Not Found) error for "POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MoHNIJT"

I have set up a frontend using React and a backend with Express Node.js. I am utilizing socket.io for communication between the client and server. Upon loading the React page, I encounter an error message that repeats every second: Failed to load resourc ...

ERROR: PipeError - Conversion of "Invalid Date" to a date is not possible for the DatePipe

While attempting to format a date with time, I ran into an error. The way I am sending the request is as follows: created = this.datePipe.transform(dateCreated, 'yyyy-MM-ddTHH:mm'); I require the time in order to consume a service that necessi ...

Guide on implementing a progress bar in JavaScript to track the download of a small file

Below is the function I created to handle an AJAX request for fetching data: var xhr = createCORSRequest('GET', url); if (!xhr) { alert('CORS not supported'); return; } xhr.onload = function() { var txt1 = xhr.responsetxt1; ...

GridView's class attribute fails to update after a button click

My GridView allows for editing information in a row by clicking on it, which opens a pop-up box where changes can be made and saved. However, after saving the changes and trying to click on another row, the pop-up box no longer appears. I have to close the ...

Unexpected result produced by indexOf() function

When trying to display the index of the first element (violet) using an alert, I am getting -1 instead of the expected result. This unexpected outcome is hindering my progress in coding. As a newcomer to JavaScript, I'm facing this issue and seeking a ...

definition of a function with another function

I'm curious about whether it's considered a good practice in JavaScript to define a function within another function. Take a look at this code snippet: module.exports = function() { function foo() { // do something } ... foo() .. ...

The building process of Ember encountered an error due to a problem with the broccoli builder

I'm currently working on an Ember project and facing an issue while trying to upgrade the version from 2.8 to 3.5.0. After changing the version and some dependencies, I encountered the following error : Error stack Even after attempting to resolve i ...

Encountering Axios 404 error while trying to access the routes directory

My server.js file in Express and Node.js contains the bulk of my back-end code, except for my database config file. The file is quite lengthy, and I want to enhance maintainability by breaking it down into smaller modules that can be imported. To start t ...

Angular FlexLayout MediaObserver: How to determine the active width using a specific div?

I am currently working on customizing the behavior of fxFlex. The web application I am working on has the capability to function as a standalone version, occupying the full screen of a web browser, as well as being embedded as a web component. It is design ...

Tips on transferring information from React frontend Hooks to the Express backend

I'm encountering an issue when attempting to send data from my React front end, which is utilizing hooks, to my Node/Express server. Upon inspecting the request object (userLog) in the Express back end, I notice that the body content is empty. Can an ...

Execute Babel task individually for each file instead of running it on the entire directory, Grunt

I've set up a Grunfile to monitor .js files in the src/ directory and trigger the babel task from https://github.com/babel/grunt-babel to generate ES5 files in the dist/ directory: module.exports = function(grunt) { require('load-grunt-task ...

Unidentified action type in Vuex: RawHTML being used in a TypeScript-powered VueJS application

Whenever I try to dispatch an action on a component, I keep getting the error '[vuex] unknown action type: RawHTML'. This issue is usually related to incorrectly namespaced modules, but in this case, I am not using any modules. store/index.ts ...

Retrieving latitude and longitude coordinates to determine percentage-based or pixel-based x and y positions

I'm currently working on extracting percentage or pixel coordinates from a latlng in leaflet maps. Here is the code snippet that sets up the map and tile layers (adapted from an app named 'maptiler') var mapMinZoom = 0; var mapMaxZ ...

Understanding the distinction between assigning a value and setting text through JSE in Selenium using C#

Utilizing the IJavaScriptExecutor to set the attribute value can sometimes result in the text box containing the set value, but not displaying it as text. In some cases, the input is sent normally to certain text boxes, while for others, it is only setting ...

Can you clarify the distinction between store.destroy() and session.destroy()? Are both necessary to use?

I am currently working on incorporating/deleting sessions in my web application, and I'm a bit puzzled because it appears that there are two different ways to destroy sessions. Should I utilize both methods - store.destroy and session.destroy, or is j ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

Step-by-step guide on entering text into a hidden field with Selenium WebDriver and Java

I am currently utilizing WebDriver in conjunction with Java for automated testing. I have come across a hidden input field within the following HTML code: <input type="hidden" value="" name="body" id=":6b"> My challenge lies in trying to input data ...

Ways to verify if an ajax function is currently occupied by a previous request

Is there a way to determine if an ajax function is occupied by a prior call? What measures can be taken to avoid invoking an ajax function while it is still processing a previous request with a readyState != 4 status? ...

What is the best way to ensure a multi-page form is validated using HTML5 and JavaScript before progressing to the next page?

Currently, there are two functionalities at play. The submit button is not being recognized while the functionality in JS $(".next").click(function(){..} is working as expected. HTML This section involves 4 fieldsets. I am attempting to validate ...

react-redux <Provider> - Empty webpage

Everything was running smoothly in my program until I integrated 'react-redux'. Now, when I try to access it on localhost, all I see is a blank page and the console spitting out this error: Uncaught TypeError: Found non-callable @@iterator Belo ...