Ways to stringify a JavaScript new date object using JSON

Extracting information from the form's JSON as users input data on the calendar

const data = JSON.stringify(orderForm.informationDate)); 

At present, I am retrieving JSON data to generate a PDF document:

{"year":2023,"month":12,"day":22}

Is there a way to convert the data into DD.MM.YYYY format?

Answer №1

Experts advise against using the dd.mm.yyyy date format, but if you're insistent

const orderForm = { informationDate: {"year": 2023, "month": 12, "day": 22} };

const ddmmyyyy = Object.values(orderForm.informationDate)
  .reverse()
  .map(val => String(val).padStart(2, '0'))
  .join('.');

console.log(ddmmyyyy); // Outputs: 22.12.2023


// Using a replacer function


const replacer = (key, value) => {
  if (key === 'informationDate')
    return Object.values(value)
      .reverse()
      .map(val => String(val).padStart(2, '0'))
      .join('.');
  return value;
}

const jsonString = JSON.stringify({ orderForm }, replacer, 2);
console.log(jsonString);

Answer №2

It seems there are some misconceptions underlying your question:

  1. JSON serialization does not support date/time data types, so dates cannot be directly serialized.

  2. When you pass a date object to the JSON serializer, it generates an object representation as seen here:

    const myExampleDate = { year: 2023, month: 12, day: 22 };
    console.log(JSON.stringify(myExampleDate)); // => {"year":2023,"month":12,"day":22}
    
  3. The format mentioned in your query seems to be a string because dates are usually stored as numbers internally, not strings.

  4. In your scenario, there are two possible solutions:

    1. Convert the date object to a string before using JSON.stringify:
      const info = {
         name: "Alice Smith",
         birthDate: {year: 1990, month: 7, day: 15}
      };
      
      info.birthDate = info.birthDate.day + '.' + info.birthDate.month + '.' + info.birthDate.year;
      
      console.log(JSON.stringify(info));
      
    2. Alternatively, utilize the "replacer" feature:
      const info = {
         name: "Alice Smith",
         birthDate: {year: 1990, month: 7, day: 15}
      };
      
      const replacerFunction = function(item) {
         if (item.year && item.month && item.day) {
           return item.day + '.' + item.month + '.' + item.year;
         }
      
         return item;
      };
      
      console.log(JSON.stringify(info, replacerFunction));
      
  5. Remember, you may need to reverse this process later on (e.g., converting the string back to a date).

  6. If you are working with Datetime objects instead of plain objects, consider checking the object class rather than the presence of day/month/year properties based on your specific code implementation.

Answer №3

To access the characteristics of this item (data.year, data.month, data.day) and combine them into a string

${data.day}.${data.month}.${data.year}

Answer №4

  1. Utilize destructuring to its full potential.
  2. The main purpose of the format function is to ensure that single-digit days and months like 2 are converted to double-digits as 02.

const date = {year: 2023, month: 12, day: 22};
const { year, month, day } = date;
const format = (str) => String(str).padStart('0', 2);
const formattedDate = `${format(day)}.${format(month)}.${year}`;
const jsonData = JSON.stringify(formattedDate);
console.log(formattedDate);
console.log(jsonData);

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

What is the functionality of Google Chrome's "New Tab" iframes?

Have you ever wondered about those 8 small iframes displaying your most visited websites? How do they capture snapshots of the websites? How are the websites chosen for display? And most importantly, how do they actually work? Edit: I want to learn how to ...

Display tables side by side using Material-UI

Presently, I am utilizing NextJs and MaterialUI to display a table with data fetched from an API created in Strapi. Challenge The current issue lies in using a table component with props that are imported into a page, where the props are mapped to an API ...

Error in Typescript persists even after short-circuit evaluation is used

Kindly review the provided code sample type type1 = string[] | undefined; let variable1 : type1 = undefined; console.log(variable1 && variable1.length); Upon attempting to run this code in Typescript Playground, an error is generated stating Pro ...

The value produced by the interval in Angular is not being displayed in the browser using double curly braces

I am attempting to display the changing value on the web page every second, but for some reason {{}} is not functioning correctly. However, when I use console.log, it does show the changing value. Here is an excerpt from my .ts code: randomValue: number; ...

Looking for a way to toggle the visibility of a dropdown list when clicking on an input in Angular7?

My Angular7 application features a dropdown menu that automatically closes when an item is selected. Additionally, I have implemented functionality to toggle the dropdown open and closed by clicking on an input field. You can view a live example of this be ...

Retrieve a specific KEY VALUE pair from a column in a SQL Server database

Within my SQL Server table, there is a Column named JsonData that contains data formatted as key/value pairs. Here is an example: {"Id":42662,"VersionNumber":0,"IsCustom":false,"SaleType":0,"RedBookSpotId":232164,"RegistrationNumber":"AUTOTEST","Price": ...

Transform the blob, which includes an image, into just an image and insert it into the <img> tag

When adding a record to a MySQL database with XAMPP and the "mysql2" package (^3.6.2), I encountered an issue. export const addPage = async (req,res) => { try { if(req.session.user !== undefined) { ...

Tips for structuring a news thread with a staggered approach

On my Drupal 8 website, I have set up a newsfeed. How can I display the news items in staggered rows? I would like the first item to align on the left and the second item to be on the right, repeating this pattern for all subsequent items. Currently, I am ...

Running a JavaScript animation within an Electron environment

My curiosity lies in developing man-machine interfaces using Electron. Currently, I am experimenting with a Star Trek life signs monitor demo. I came across this code that can be easily customized to create vertical and horizontal movements: http://jsfiddl ...

Obtaining JSON data from a PHP script using AngularJS

I've been exploring an AngularJS tutorial on a popular website called w3schools. Check out the tutorial on w3schools After following the tutorial, I modified the script to work with one of my PHP scripts: <!DOCTYPE html> <html > <sty ...

What could be the reason that the results of my quick sort function are not appearing on the screen

I'm having trouble getting any output from this code. Can someone help me figure out what's wrong? function Ascending() { var array = new Array(); array[0]=parseInt(document.getElementById("1").value); array[1]=parseInt(document.getElementById(" ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...

What causes a globally declared array to remain empty in the global scope even after data is pushed to it within a callback function?

Initially, I set an empty array as the value for the global variable artistURLs. Then, within the Cheerio .each() iterator method, I push strings (stored in the local variable artistURL) into the artistURLs array. var request = require('request&apos ...

Security Measures for Parsing Arrays using eval() Function

When I receive a string of an array containing objects via an http request, I use eval() to parse it. Since I am expecting an array object after parsing, how can I secure this eval() process beyond using if (Array.isArray(parsedObj)) ... Is there a bette ...

Converting a string date format to UTC: A step-by-step guide

In my Typescript code, I am trying to convert a date/time format from string to UTC format but currently facing an issue with it. The desired output is as follows: 2018/10/27+16:00 => 20181027T01000Z import * as moment from 'moment' dates=$ ...

Insert a span element before an HTML input using JavaScript

On my webpage, there is an html input inside a div. Here is what it looks like: <input type="text" class="form-control" placeholder="Barcode" role="barcode"> Using JavaScript only, I am trying to add the following code into the DOM above it: <s ...

Creating pages or tabs within a table using HTML5 and Angular is a simple and effective way to organize

I have a REST response that returns around 500 records. These records are being displayed in an Angular table. I would like to add customization options for the user, allowing them to choose to display 10/20/30... records per page. Additionally, I want to ...

Determine the number of occurrences of specific values within a group of objects based on a

I have the following dataset: const data2 = [ { App: "testa.com", Name: "TEST A", Category: "HR", Employees: 7 }, { App: "testd.com", Name: "TEST D", Category: "DevOps", Employee ...

Animations of bezier curves created with Three.js

UPDATED: SOLUTION FOUND I am in need of guidance on how to create animation for the movement of points along a curve to simulate string motion in 3D while keeping performance in mind. Imagine multiple strings between two points, for example. Check out t ...

Pause page scrolling temporarily in JavaScript while allowing the scrollbar to continue scrolling until the pause is lifted

I'm currently working on achieving a similar effect to the one found on this website: . On that site, as you scroll down, the 'HELLO' text moves to the side. I've managed to do that part successfully, but I'm facing an obstacle reg ...