What is the best way to retrieve the date in JavaScript and format it as day, month, year?

Currently, I am working on converting a UNIX timestamp to a date object and have successfully managed to split the returned date using the split() method. This is my current code:

var randomDate = new Date(1571990933 * 1000).toString().split('T');
console.log(randomDate[0]);

The output I am currently getting is: Wed Oct 30 2019 14:30:30 GM

However, what I actually want as output is: 30. October 2019

Can anyone provide some guidance on how I can achieve this desired output?

Answer №1

Generate an array called months that maps index to human-readable month names. Then, use date.get methods for day, month, and year to construct your date string.

const getDate = () => {
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const date = new Date(1571990933 * 1000);
  return `${date.getDay()}. ${months[date.getMonth()]} ${date.getFullYear()}`
}

Answer №2

If you have the option to use a library like moment.js, it simplifies everything for you :

console.log( moment( new Date(1571990933 * 1000) ).format('D[.] MMMM YYYY') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

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

Why aren't functions included when casting from a JSON literal to a specific type?

In my model class, the structure looks like this: export class Task { public name: string; public status: string = "todo"; public completeTask(): void { this.status = "done"; } } There is also a service responsible for retrie ...

Utilizing the onclick event to call a function with multiple arguments within Template literals

How can I properly write a function with multiple arguments using JavaScript post ES6 template literals when called by an onclick event? Here is my code: function displayImg(imageUrl, gameName, gameSummary, gameYear, cardId) { cardId = cardId.toStrin ...

Find the index of two numbers in an array that equal a target sum

[https://drive.google.com/file/d/12qIWazKzBr1yJGpo1z106euXVJMKMwEa/view?usp=sharing][1]I am struggling to find the correct indices of two numbers in an array whose sum equals a target number provided as an argument. I attempted to solve this using a for ...

Executing a JavaScript function by utilizing the # symbol in the URL: Tips and Tricks

It all began with a function called loadround that changed the innerHTML of an iframe. The links within the iframe would then change the page when clicked, but hitting the back button made the loadround page vanish. I pondered over this issue multiple time ...

Error in Node.js Express: Attempted to access property 'image' of null resulting in an unhandled error event

I've been trying to identify where the issue lies. Can someone lend a hand with this? When attempting to submit the post without an image, instead of receiving a flash message, the following error pops up: and here's the source code link: https: ...

The poolSize for Mongoose 4.8.1 seems to be capped at 2 and will not increase further

I'm experiencing an issue where the MongoDB poolSize for connects does not exceed 2, no matter what value I set it to. Running on NodeJS v7.4.0 Using Express v4.14.1 With Mongoose v4.8.1 Here's a snippet of the code: let database_uri = ' ...

Choosing JavaScript

<select> <script type="text/javascript"> $.get( 'http://www.ufilme.ro/api/load/maron_online/470', function(data){ var mydata = new Array(); var i = 0; // индекс масси ...

Modify the JSON object once it has been imported into Three.js

I am diving into the world of JavaScript and exploring Three.JS, a fascinating new frontier for me. Recently, I managed to convert an obj file into a JSON object and successfully loaded it onto my website using THREE.JSONLoader in three.js. The object disp ...

Submitting an ASP.NET MVC form with jQuery and passing parameters

Having trouble passing the ThreadId parameter when submitting a form to my controller through jQuery Ajax. The code works fine, but for some reason, the ThreadId doesn't get passed using form.serialize(). Any suggestions on how to effectively pass par ...

Mocking an Angular method for an element

Currently, I am experimenting with a directive where I am incorporating the Mobiscroll library. Despite being aware of Mobiscroll's angular components, I am opting to work with older versions of the library for now. The challenge I am facing involves ...

The input text in the Typeahead field does not reset even after calling this.setState

As I work on creating a watchlist with typeahead functionality to suggest options as the user types, I encountered an issue where the text box is not resetting after submission. I attempted the solution mentioned in this resource by calling this.setState( ...

Navigating through directories up to the first level using the walk module in nodejs

Below is the directory structure that I have: Ranveers-MacBook-Air:custom-feeds ranveer$ ls /Users/ranveer/custom-feeds README.md cartridges sites Ranveers-MacBook-Air:custom-feeds ranveer$ I am looking to traverse the above directory and only dis ...

Updating rows by their unique identifier can be easily accomplished by utilizing the

I am currently facing an issue while trying to update a row by its Id using Java, MySQL, and AngularJS. The problem is that I keep receiving a false response and no changes are reflected in the database. Below is my Java function: public boolean modifyCl ...

What is the best method for determining the input values based on the changing range slider values?

Having some jquery issues currently. I am utilizing an ionrange slider to retrieve values, and then I need to apply conditions using if else statements (around 5-7 conditions) based on these values and display them in another input field. However, the desi ...

Executing Code from Tab only upon tab activation

I have multiple tabs on my page, and I want to have one tab with a widget that only loads when the user clicks on it, instead of loading along with all other tabs when the page loads. <div class="tabbable tabbable-custom"> <ul class="nav nav-t ...

I'm struggling to find the perfect configuration for Vite, JSconfig, and Aliases in Visual Studio Code to optimize Intellisense and Autocomplete features

After exclusively using PHPStorm/Webstorm for years, I recently made the switch back to Visual Studio Code. The main reason behind this decision was the lightweight nature of VSCode and its widespread availability as a free tool, unlike paid services. I s ...

How to align a div horizontally without any line breaks

Looking for a solution to align "container-element" divs horizontally without creating a newline? <div id='container'> <div class='container-element' id='el0'></div> <div class='container-element ...

Animate div visibility with CSS transitions and Javascript

I'm currently working on incorporating an animation into a div that I am toggling between showing and hiding with a button click. While I have the desired animation, I am unsure of how to trigger it using JavaScript when the button is clicked. Can any ...

Javascript - Accessing a specific element in an array using a variable

I am currently developing a webpage that interacts with a CGI backend. While the CGI backend is functioning well, my limited knowledge of JavaScript is making it hard for me to manage the results retrieved from AJAX JSON requests. Here's what I have: ...

Utilize JSON text importing for template literals in Node.js

When it comes to my node js projects, I usually opt for using a text.json file and requiring it rather than hardcoding static text directly into my code. Here's an example: JSON file { "greet": "Hello world" } var text = require('./text.json ...