Vinay N
Vinay N

Reputation: 269

How to split strings in javascript?

I want to split the datetime in the below object to date and time separately.

 let A = {
   datetime: '2019-02-01 15:30:43' 
 }

And save it in two different variables.

Upvotes: 0

Views: 78

Answers (2)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

You can use moment.js library if you don't want any surprises.

moment(A.datetime).format('L'); // get date only

moment(A.datetime).format('LTS') // get time only.

You can have specific date and time format as well when using momentjs.

You may also use JavaScript's Date class for this.

const date = new Date(A.datetime);

//to get date
date.getDate() +' '+date.getMonth()+' '+date.getFullYear();

//to get time.
date.getHours()+' '+date.getMinutes()+' '+date.getSeconds();

Upvotes: 2

user5283119
user5283119

Reputation:

You can use split() e.g.

var splitString = A.datetime.split(" ");
// Returns array, ['2019-02-01','15:30:43']

You can access this with splitString[0] for the date and splitString[1] for the time.

Upvotes: 2

Related Questions