Parsing dates arriving from a Restful Service in JavaScript

When I make a Restful call, the JSON response contains dates in a strange format like this:

/Date(-62135568000000)/

What is the simplest way to convert it to a normal date format like (January 10, 2016)?

I have read some articles that suggest using regex functions, but I believe there must be an easier and more concise solution in JavaScript. Any suggestions?

Answer №1

Uncertain of how that specific date is interpreted, I wasn't able to bring it close to 2016. However, you can structure it in this manner:

const date = '/Date(-62135568000000)/'

const zeroPad = num => num < 10 ? '0' + num : num

const monthify = month => {
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', '...']
  return months[month]
}

function parseDate(dateString) {
  const dateValue = new Date(parseInt(dateString.match(/(\d+)/)[1]) / 100)
  const parts = [
    monthify(dateValue.getMonth()), ' ', 
    zeroPad(dateValue.getDate()), ', ',
    dateValue.getFullYear()
  ]
  return '(' + parts.join('') + ')'
}

console.log(
  parseDate(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

Error: The build process for Next.js using the command `npm run build`

Currently attempting to construct my application with target: 'serverless' set in the next.config.js file (in order to deploy on AWS Lambda). Upon running npm run build, I am encountering the following output: Warning: Built-in CSS support is bei ...

react-responsive-carousel: setting a specific height for thumbnail images

After setting a fixed height for the image, I noticed that the same height is also being applied to the thumbnails. How can I avoid this issue? <Carousel width="600px" dynamicHeight={false}> {data?.book?.images.map((image, i) => ( ...

Developing unit tests for a module responsible for generating Json REST services

Just completed working on https://github.com/mercmobily/JsonRestStores. Feeling a bit nervous since I haven't written any unit tests yet. This module is quite complex to test: it enables the creation of Json REST stores and direct interaction with th ...

The arrangement of imports in NodeJS can lead to unexpected errors

Having an issue with the order in which I include different models in my main server.js file using NodeJS. Below is the code from my product.js Product model file: var mongoose = require("mongoose"); var Dealer = require("./dealer.js") var productSc ...

Communicating with Controllers: Troubleshooting Module Issues in Angular JS

Currently, I am in the process of learning Angular through this informative video: http://www.youtube.com/watch?v=LJmZaxuxlRc&feature=share&list=PLP6DbQBkn9ymGQh2qpk9ImLHdSH5T7yw7 The main objective of the tutorial is to create a rollover effect ...

Strategies for retrieving the latest content from a CMS while utilizing getStaticProps

After fetching blog content from the CMS within getStaticProps, I noticed that updates made to the blog in the CMS are not reflected because getStaticProps only fetches data during build time. Is there a way to update the data without rebuilding? I typica ...

Determine the maximum size of a specified number of square divs that can fit within responsive parent divs

I am working on creating a grid of square divs inside a container with variable height and width. The number of square div's is predetermined. All square divs will have images with the same dimensions (similar to the example). They should align left ...

"Although Vuex data is present, an error is being logged in the JavaScript console

I'm utilizing Vuex to retrieve data from a URL and I need to use this data in computed properties in Vue.js. What could be causing the issue? <script> import {mapGetters, mapActions} from "vuex"; computed: { ...mapGetters(["ON ...

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

Implementing Isotope layout in Reactjs with data-attributes for filtering and sorting content

I am currently working on optimizing the isotope handler within a react component. My goal is to implement filter options such as category[metal] or category[transition], as well as combo filters like category[metal, transition]. Here is the sandbox for t ...

Guidelines for embedding a JSON file or object within C++ during compilation

I have a JSON file named env-config.json containing database environment configuration data structured like this: { "LATEST":{ "DB_DATABASE":"databasename", "DB_HOST":"hosturl", "DB_PORT":"3306", "DB_USER":"root", "POOL_MAX":1 }, "PROD":{ "DB_DATABASE":"d ...

How can you efficiently manage Access & Refresh tokens from various Providers?

Imagine I am allowing my users to connect to various social media platforms like Facebook, Instagram, Pinterest, and Twitter in order to use their APIs. As a result, I obtain access tokens for each of these providers. Based on my research, it seems advisa ...

Utilizing the power of JavaScript/JQuery to showcase a compilation of all input values within an HTML form

I'm struggling to showcase all the input values from my HTML form on the final page before hitting the "submit" button. Unfortunately, I am facing a challenge as the values are not appearing on the page as expected. Despite several attempts, the valu ...

In my current project, I am working with Knockout and TypeScript but I am encountering difficulties in firing the window-resize event

Instead of using jquery, I prefer working with a custom handler for the $(window).resize(function () { ... event. If there is a way to achieve this without relying on jquery, please feel free to share it in the comments below. The code snippet below show ...

Transforming the text to a new line

I have been attempting to format lengthy texts from a JSON file, but I haven't been successful. The text keeps displaying as multiple sections within a single response, which can be seen in the image below. I've tested solutions like word-break a ...

Achieve rapid Key-Value Coding with empty values using NSDictionary

Unsure if the question has been named correctly but here is the scenario: Imagine a JSON response returned from an API, which is then parsed using SBJson with great success. An example of the JSON structure includes: { "value": 15199, //this ...

Progress bar carousel component based on advancement movements

Here is the mockup I am working with: https://i.sstatic.net/bIepQ.png So far, I have made good progress with this code: https://codesandbox.io/s/codepen-with-react-forked-16t6rv?file=/src/components/TrendingNFTs.js However, I am facing a couple of challe ...

When implementing javascript_pack_tag in Rails, an EOFError may occur

It seems like the files in public/packs/js are having trouble loading. Here are the javascript tags being used in the view: = javascript_include_tag 'application' = javascript_pack_tag 'application' The error displayed in the browser ...

LESS — transforming data URIs with a painting mixin

Trying to create a custom mixin for underlining text, similar to a polyfill for CSS3 text-decoration properties (line, style, color) that are not yet supported by browsers. The idea is to draw the proper line on a canvas, convert it to a data-uri, and the ...

Failure to Trigger AJAX Success Event

I am facing an issue while trying to retrieve a JSON string using an ajax call with JQuery. Despite getting a code 200 and success from the complete method, the success method itself is not triggering. function initialize() { $.ajax( { type ...