Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Date in React

I retrieve a date variable from a JSON object in a string format, but I am having trouble getting the elapsed time until now.

import React from 'react';

export default class Date extends React.Component {
render() {

    console.log(this.props.date); //shows: 2017-01-25T10:18:18Z

    var date = Date.parse(this.props.date.toString());

    console.log(date.getTime());

    return (
        <div >
      </div>
    );
   }
}
like image 656
Nedjim DN Avatar asked Jan 25 '17 14:01

Nedjim DN


People also ask

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do I convert a date to a string in react?

Using new Date() constructor The new Date() constructor takes the date string as an argument and creates the new date object. The toString() method returns the string representation of the specified date.

How do I convert a string to a date in TypeScript?

Use the Date() constructor to convert a string to a Date object in TypeScript, e.g. const date = new Date('2024-07-21') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.

What is new Date () in react?

Using new Date() constructor We can use the new Date() constructor to get the current date in a react component. The new Date() constructor creates a new date instance that contains the following methods to construct the full date. getDate() method: It returns the day of the month.


1 Answers

If it is not a date object, just create a new date object.

 var date = new Date(this.props.date); 
 var elapsed = date.getTime(); // Elapsed time in MS

If it is a date object, just call this.props.date.getTime()

like image 112
Chase Avatar answered Sep 20 '22 20:09

Chase