Haq.H
Haq.H

Reputation: 973

How to compare Date Time Strings format: (YYYY-MM-DD XX:YY) in javascript

I have a array of these date Times. They are provided as strings. I need to be able to isolate the min dateTime and the max dateTime of the provided array but I am having trouble figuring out how I can do this? Is it possible to feed each string to -> new Date(dateTime) and then compare the two objects that way? Or do I have to parse then compare the date and compare time separately?

example values:

  4: "2018-11-15 00:16"
  5: "2018-11-15 00:52"
  6: "2018-11-15 02:24"
  7: "2018-11-15 03:02"
  8: "2018-11-15 02:49"
  9: "2018-11-15 00:14"
  10: "2018-11-15 02:20"

In this example I would need to isolate 9 as the min and 7 as the max value in the array

Upvotes: 3

Views: 2125

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92417

ONELINER: not fastest ( O(nlogn) ) but short code - I assume your strings with dates are in array a

let min=a.sort()[0], max=a.slice(-1)[0];

result is in varaibles min and max, working example HERE

Upvotes: -1

trincot
trincot

Reputation: 350272

Reading the other answers I cannot but raise the points that:

  • no conversion to Date is needed
  • sorting has a O(nlogn) time complexity, while looking for the min/max can be done in O(n) time.

var arr =["2018-11-15 00:16", "2018-11-15 00:52", "2018-11-15 02:24", "2018-11-15 03:02", "2018-11-15 02:49", "2018-11-15 00:14", "2018-11-15 02:20"];

var minDate = arr.reduce((a, b) => a < b ? a : b);
var maxDate = arr.reduce((a, b) => a > b ? a : b);

console.log("min", minDate, "at index", arr.indexOf(minDate));
console.log("max", maxDate, "at index", arr.indexOf(maxDate));

Upvotes: 2

gatsbyz
gatsbyz

Reputation: 1075

In Typescript:

const dates = ["2018-11-15 00:16", "2018-11-15 00:52", ...];
const sortedDates = dates.sort();
const minDate = sortedDates[0];
const maxDate = sortedDates[sortedDates.length - 1];

And yes you can do :

new Date("2018-11-15 00:16") < new Date("2018-11-15 00:52") => true

Upvotes: 4

Related Questions