Timestamp in Unix format showing only the month and year

Is there a more concise way to convert the month and year from an array of dates into Unix timestamps without resorting to verbose code? I currently have a solution, but it is lengthy and cumbersome as I iterate over each date in the array. Any suggestions for simplifying this process?

// JavaScript code
    // Inserted code snippet here for demonstration purposes

This is how my current array is structured:

// JavaScript code
    // Inserted code snippet here for demonstration purposes

This is what the resulting array should look like:

// JavaScript code
    // Inserted code snippet here for demonstration purposes

Answer №1

To easily create a new date instance, you can utilize the month (converted to an index) and year from the string.

By using an array of months to convert the named month to an index and dividing the result by 1000, you can align javascript's milliseconds with unix's seconds.

const arr = [{ post_title: 'title', post_date: 'December 2021', }, { post_title: 'title', post_date: 'November 2021', }, { post_title: 'title', post_date: 'October 2021', }, { post_title: 'title', post_date: 'September 2021', }, { post_title: 'title', post_date: 'August 2021', }, { post_title: 'title', post_date: 'July 2021', }, { post_title: 'title', post_date: 'June 2021', },];

const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December',]; 

const result = arr.map((o) => {
  const [month, year] = o.post_date.split(' ');

  return {
    ...o,
    unix_timestamp: new Date(year, months.indexOf(month)).valueOf() / 1000,
  };
});

console.log(result);

Please note: months are indexed starting at 0 for January and ending at 11 for December

Answer №2

Who needs a lookup table anyway?

const dataSet = [{ title: 'Sample Title', date: 'December 2021' }, { title: 'Another Title', date: 'November 2021' }, { title: 'New Title', date: 'October 2021' }, { title: 'Title Here', date: 'September 2021' }, { title: 'Current Title', date: 'August 2021' }, { title: 'Old Title', date: 'July 2021' }, { title: 'Previous Title', date: 'June 2021' }];

const convertedData = dataSet.map(item =>
    ({...item,
    unix_time: new Date(item.date.replace(" ", " 1. ") + " 00:00:00").valueOf() / 1000}));

console.log(convertedData);

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

The tutorial on setting up a shopping cart using passport, mongo, and express experiences a delay when clicking the submit button after making

When using passport authentication and submitting the form with all validations passing, there is an issue where the application does not redirect to the specified route upon successful redirection. Instead, it simply loads and eventually crashes. I am cur ...

Selenium fails to detect elements that are easily located by the browser using the aba elements, as well as through the use of JavaScript in the console

Looking to automate actions on the bet365 casino platform, but facing challenges with bot blocking mechanisms. Visit: Struggling to interact with elements within the "app-container" div using Selenium, however able to access them via JavaScript in the br ...

The Vuex state keeps acting mysterious by claiming to be undefined

Here is my post.js located in src > store > post.js: import Vuex from 'vuex' import Vue from 'vue' import axios from 'axios' Vue.use(Vuex) export default new Vuex.Store({ state: { testState: 'Hello&apo ...

What is the best way to incorporate a toggle hamburger animation into the mobile menu using WordPress and JavaScript?

Looking to add a toggle hamburger animation to my mobile menu on WordPress. I tried following a tutorial where the JavaScript code had separate "Open" and "Close" buttons as icons. Although I have a hamburger menu, I'm struggling with understanding ho ...

"Performing a MongoDB Node query within the time frame of 1 hour from

I am having trouble retrieving data with my query to find all objects within the last hour based on timestamps: Here is the schema I am using: var visitSchema = mongoose.Schema({ timestamp: { type: Date, default: Date.now }, userID: String, userName ...

Accessing the hashtag portion of the URL in Nuxt

this.$route.path retrieves the URL without the hashcode at the end. Is there a way to obtain the hash part of the URL or the entire URL so that I can properly separate the hash part? Just to clarify, for a URL like https://example.com#test, I am trying to ...

Clicking on the button has no effect whatsoever

I'm currently dealing with a button on my webpage that seems to be causing me some trouble: <script> function changeMap() { container.setMap(oMap); } </script> <button onClick="changeMap"> Click here </button> Upon inspe ...

What is the best way to display two cards while concealing a third one using a "show more"

Is there a way to hide certain cards by default and only show them when the user clicks on a "View more" button? I have multiple cards, but I want to hide the last one initially and reveal it when the button is clicked. I would really appreciate any assis ...

Using C++ const char along with the functions .begin() and .end()

In my code, I have a program that is structured as follows: const char *Argv[] = {"thing", "thing1", "thing3"}; bool pass = xxxxx::yyyyy(Argv.begin(), Argv.end(), Tri); I believe this might be invalid because const char * is not a custom-defined type. B ...

Is there a method or API available for interacting with an <object> that is currently displaying a video?

Yay, I figured it out! I've been using video.js to play videos on a website that needs to work offline too. Unfortunately, using flash is not an option due to compatibility issues. So, I decided to write my own fallback solution. For Internet Explor ...

Encapsulating the React Material-ui Datepicker and Timepicker OnChange event callback functionging

I'm new to React and currently incorporating Material-UI into my project for additional UI components. I've noticed some repetitive code that I'm finding difficult to refactor due to constraints within a Material-UI component's implemen ...

Using jQuery's Ajax function to specify a dataUrl before sending the request

There seems to be an issue with this AJAX request. The 64-Value-String is not being returned in the beforeSend handler, but it does show up in an alert. I am unsure how to handle this asynchronously. Can someone help me troubleshoot? $imageMaps[0] = &apos ...

Transferring a JSON value to PHP and saving it in a MySQL database

I currently have JSON values stored in a variable called json_obj in JavaScript. My goal is to pass this data on submission and store it in a MySQL database using PHP. However, I am unsure of how to achieve this. var json_obj = [ {"id":"1","name":"mun ...

What is the best way to locate this particular element on the webpage?

After using the right-click and selecting inspect element, I located the code of the desired element on the webpage: <input type="text" ng-if="!editing" ng-model="item.Price" ng-click="inputFocus()" ts="" required="" placeholder="قیمت :" class="ng- ...

Tips for navigating through lengthy webpages using the jQuery onepage-scroll plugin

I recently came across a fantastic plugin called onepage-scroll that almost perfectly fits my requirements. However, I have encountered an issue. Some of my pages, defined within <section> tags, are larger than a single screen. Is there a way to cust ...

How to effectively combine HTML on both the server-side and through JavaScript generation?

Despite my usual creativity, I'm struggling to find a solution right now. The HTML being generated, whether it's form rows or table rows, is the same whether it's done through javascript or on the server side. This duplication of generation ...

How can you use CSS animations to animate two images in a way that hides one while showing the other?

click here for the image link visit this webpage for the link I need I am looking to add an animated section to my website. The inspiration comes from the webpage linked above, where images slide down one after another in a seamless manner. I attempted t ...

Retrieve the JSON element from a Backbone model by its unique identifier

I'm diving into Backbone for the first time and I'm facing difficulties making it work smoothly with a JSON data file. Here's how my model looks: window.Test = Backbone.Model.extend({ defaults: { id: null, name: null, }, url: f ...

Is it common for Google Chrome console snapshots to have a prolonged idle time?

I noticed in Google Chrome console snapshot that my JavaScript code has a long "Idle" time. I'm not sure if this is normal. Attached is a screenshot for reference: https://i.stack.imgur.com/k0mkp.png Could this extended "Idle" time be attributed to ...

Utilize Laravel 8 and Vue Js to dynamically showcase retrieved data in input fields

I am facing a challenge with my Laravel 8 registration form using Vue js. Before submitting the form, I need to verify if the referring user exists in the database. If the user is found, I want to dynamically display their full name in an input field upon ...