ArticleZip > Function To Convert Timestamp To Human Date In Javascript Duplicate

Function To Convert Timestamp To Human Date In Javascript Duplicate

Have you ever come across a timestamp in your JavaScript code and wished you could easily convert it into a human-readable date format? Well, you're in luck! In this guide, we're going to dive into writing a simple and efficient function that will do just that for you.

#### The Problem
Let's say you have a timestamp value like `1634037600`, which is hard to decipher for most of us. Wouldn't it be more convenient to see this as "October 12, 2021" instead? Our goal is to create a function that can make this conversion quick and straightforward.

#### The Solution: Writing the Function
To start off, let's create a function named `convertTimestampToDate` that takes in a timestamp as a parameter. Here's a basic outline of our function:

Javascript

function convertTimestampToDate(timestamp) {
  // code implementation will go here
}

We will implement the code inside our function to achieve the desired date format. First, we'll convert the given timestamp to milliseconds and then create a new Date object from it. This can be done using the JavaScript `Date` constructor as follows:

Javascript

function convertTimestampToDate(timestamp) {
  const milliseconds = timestamp * 1000;
  const dateObject = new Date(milliseconds);

  // more code will be added here
}

Next, we can extract specific date components from the `dateObject` such as the day, month, and year. JavaScript provides several useful methods for this purpose. We can now proceed to format these components into a more readable output. Here's the complete implementation of our function:

Javascript

function convertTimestampToDate(timestamp) {
  const milliseconds = timestamp * 1000;
  const dateObject = new Date(milliseconds);

  const options = { year: 'numeric', month: 'long', day: 'numeric' };
  const formattedDate = dateObject.toLocaleDateString('en-US', options);

  return formattedDate;
}

#### Testing Our Function
Let's put our function to the test by converting a timestamp value and logging the result to the console:

Javascript

const timestamp = 1634037600;
const humanDate = convertTimestampToDate(timestamp);

console.log("Human-Readable Date:", humanDate);

When you run this code snippet, you should see the transformed date printed to your console in a much more familiar format.

#### Conclusion
By creating a simple JavaScript function as demonstrated above, you can effortlessly convert timestamps into human-readable dates. This can be incredibly useful when dealing with timestamps in your projects and needing to present them in a more user-friendly way. Feel free to adapt this function to suit your specific requirements and happy coding!