Confirm two dates of this format "dd-MMM-yyyy" in javascript

I have two dates 18-Aug-2010and 19-Aug-2010the format. How to determine which date is longer?

+3
source share
5 answers

You will need to create a custom parsing function to process the desired format and get a mapping of date objects, for example:

function customParse(str) {
  var months = ['Jan','Feb','Mar','Apr','May','Jun',
                'Jul','Aug','Sep','Oct','Nov','Dec'],
      n = months.length, re = /(\d{2})-([a-z]{3})-(\d{4})/i, matches;

  while(n--) { months[months[n]]=n; } // map month names to their index :)

  matches = str.match(re); // extract date parts from string

  return new Date(matches[3], months[matches[2]], matches[1]);
}

customParse("18-Aug-2010");
// "Wed Aug 18 2010 00:00:00"

customParse("19-Aug-2010") > customParse("18-Aug-2010");
// true
+8
source

You can parse manually for a given format, but I suggest you use the date.js library to parse dates, then compare. Check it out, it's awesome!

, , js utility.

+3

Date "MMM + dd yyyy", :

function parseDMY(s){
  return new Date(s.replace(/^(\d+)\W+(\w+)\W+/, '$2 $1 '));
}
+parseDMY('19-August-2010') == +new Date(2010, 7, 19) // true
parseDMY('18-Aug-2010') < parseDMY('19-Aug-2010')     // true
+3

-, "dd-MMM-yyyy" Date ( " " ), . Date .

function parseMyDate(s) {
    var m = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
    var match = s.match(/(\d+)-([^.]+)-(\d+)/);
    var date = match[1];
    var monthText = match[2];
    var year = match[3];
    var month = m.indexOf(monthText.toLowerCase());
    return new Date(year, month, date);
}

Date ( 1970 , ), :

if (parseMyDate(date1) > parseMyDate(date2)) ...
+1

: IE10, FX30 (, , ) "18 2010" - Chrome

Date.parse("18-Aug-2010".replace("/-/g," ")) ( )

Live Demo

,

function compareDates(str1,str2) {
  var d1 = Date.parse(str1.replace("/-/g," ")),
      d2 = Date.parse(str2.replace("/-/g," "));
  return d1<d2;
}
0

Source: https://habr.com/ru/post/1760245/


All Articles