0

I've got multiple dictionaries with dates in and I need to find the highest one. To compare the dates I get the date from the dictionary, convert it using new Date(dateString) to be able to compare the dates to get the latest date.

The dateString looks like this: 2019-03-07 08:40:16

I convert this using new Date(dateString) and it looks like this:
Thu Mar 07 2019 08:40:16 GMT+0000 (Greenwich Mean Time)

I then need to convert it back to original format YYYY-MM-DD HH:MM:SS

What is the best way to do this, I thought there would be something where you could define the output format for new Date() but can't find anything.

Any help is appreciated.

JackU
  • 1,105
  • 3
  • 10
  • 29

2 Answers2

1

I'd recommend you to use Moment https://momentjs.com/ lib for time comparison and formatting.

const date1 = moment('2019-03-06 08:40:16', 'YYYY-MM-DD HH:mm:ss');

const date2 = moment('2019-03-07 08:40:16', 'YYYY-MM-DD HH:mm:ss');

const isBefore = date1.isBefore(date2);

console.log('isBefore', isBefore);

console.log('formatted date:', date2.format('YYYY-MM-DD HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Igor Litvinovich
  • 1,828
  • 8
  • 19
0

This is surely ain't the most elegant solution but based on the conversion from dateString, you can reconstruct it using the Date() objects built-in methods.

var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
var temp2 = "" + temp.getFullYear() + "-" + (temp.getMonth() + 1) + "-" + temp.getDate() + " " + temp.getHours() + ":" + temp.getMinutes() + ":" + temp.getSeconds();
console.log(temp2);

If you plan to do this with multiple dates, you might consider enhancing the Date object with your own method like:

Date.prototype.reformat = function() {
  return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate() + " " + this.getHours() + ":" + this.getMinutes() + "." + this.getSeconds();
}
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
console.log(temp.reformat());
obscure
  • 8,071
  • 2
  • 9
  • 30