Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: convert datetime to DD/MM/YYYY - Time?

I have a datetime that looks like this:

2017-04-17 18:26:03

How can I convert this to this format using javascript or jquery:

17/04/2017 18:26

I found this question which I thought might help me but the answers are converting a timestamp but mine is not a time stamp.

How to convert a DateTime value to dd/mm/yyyy in jQuery?

like image 390
David Hope Avatar asked Sep 18 '25 03:09

David Hope


2 Answers

You can use simple string and array manipulation.

const dateTime = '2017-04-17 18:26:03';
const parts = dateTime.split(/[- :]/);
const wanted = `${parts[2]}/${parts[1]}/${parts[0]} ${parts[3]}:${parts[4]}`;
console.log(wanted);

Additional: If you don't have an environment that supports Template Literals then you can write it like this.

const dateTime = '2017-04-17 18:26:03';
const parts = dateTime.split(/[- :]/);
const wanted = parts[2] + '/' + parts[1] + '/' + parts[0] + ' ' + parts[3] + ':' + parts[4];
console.log(wanted);
like image 54
Xotic750 Avatar answered Sep 20 '25 18:09

Xotic750


You could use a regular expression within a replace call:

input.replace(/^(\d+)-(\d+)-(\d+)(.*):\d+$/, '$3/$2/$1$4');

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

Explanation

  • ^: match start of the string.
  • (\d+): capture group that matches digits. A captured group can be back-referenced with $1 for the first group, $2 for the second ... etc. in the second argument.
  • :\d+$: match a colon followed by digits and the end of the string ($): as this is not captured, this part (seconds) will be omitted in the result.
like image 33
trincot Avatar answered Sep 20 '25 17:09

trincot