David Hope
David Hope

Reputation: 1536

Javascript: convert datetime to shorter format?

I have a string of datetime that looks like this:

2017-04-17 18:26:03

I can use javascript to reformat and shorten it like so:

var input = '2017-04-17 18:26:03';
var result = input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1');

console.log(result);

/////Prints This: 17/04/2017///

Now, I need to make it even shorter like this:

17/04/17

Could someone please advice on this?

Any help would be appreciated.

EDIT: I don't want to use anything like moment.js or any other library as it is overkill.

Upvotes: 0

Views: 104

Answers (2)

Damien
Damien

Reputation: 4093

You're right, moment.js is overkill to do it. But I'm not sure regex are the fastest way to do that and it isn't the most readable. Moreover Date object has methods to do it. For example you can use toLocaleDateString() :

const date = new Date('2017-04-17 18:26:03');

const formattedDate = date.toLocaleDateString("en-GB", {
    year: "2-digit",
    month: "numeric",
    day: "numeric"
});

console.log( formattedDate ); // "17/04/17"

And if you are concerned about performance, when formatting a lot of dates, it is better to create an Intl.DateTimeFormat object and use the function provided by its format property :

const date = new Date('2017-04-17 18:26:03');

const dateFormatter = new Intl.DateTimeFormat("en-GB", {
    year: "2-digit",
    month: "numeric",
    day: "numeric"
});

const formattedDate = dateFormatter.format(date);

console.log( formattedDate ); // "17/04/17"

Upvotes: 2

Mark Reed
Mark Reed

Reputation: 95252

If you're using a regex, you can just take the year modulo 100 when building the string:

let match = input.match(/^(\d+)-(\d+)-(\d+)\s+(\d+):(\d+):(\d+)$/)
let result = `${match[3]}/${match[2]}/${match[1] % 100}`
console.log(result)
//=> '17/4/17'

Upvotes: 1

Related Questions