Samuel
Samuel

Reputation: 6136

Javascript: Removing part of a string ( get date string )

I simply need to remove the time from this string Sun Apr 26 2020 01:00:00 GMT+0100 (BST)

Current solution which works

const dateTime = 'Sun Apr 26 2020 01:00:00 GMT+0100 (BST)';
const dateTimeArray = dateTime.split(' ');
const date = dateTimeArray.splice(0, 4);
console.log(date.join(' ')); // Correctly returns 'Sun Apr 26 2020'

Although this works I'm wondering if theres a more elegant? Or perhaps a regex?

Upvotes: 1

Views: 116

Answers (3)

hirsch
hirsch

Reputation: 11

You could try

const dateTime = 'Sun Apr 26 2020 01:00:00 GMT+0100 (BST)';
const date = dateTime.substring(0, 15);
console.log(date);

Upvotes: 1

Sean Bright
Sean Bright

Reputation: 120654

Just use String.substring():

const dateTime = 'Sun Apr 26 2020 01:00:00 GMT+0100 (BST)';
console.log(dateTime.substring(0, 15));

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

You can use toDateString

const dateTime = 'Sun Apr 26 2020 01:00:00 GMT+0100 (BST)';

console.log(new Date(dateTime).toDateString())

Upvotes: 4

Related Questions