Convert string to date in jQuery and Internet Explorer?

I want to convert a date string to a date object in jQuery, and the code below is great for Chrome and Firefox, but not Internet Explorer:

<script type="text/javascript" charset="utf-8">
//Validate if the followup date is now or passed:
    jQuery.noConflict();
    var now = new Date();
    jQuery(".FollowUpDate").each(function () {
        if (jQuery(this).text().trim() != "") {
            var followupDate = new Date(jQuery(this).text().trim()); //Here the problem
            alert(followupDate);
            if (followupDate <= now) {
                jQuery(this).removeClass('current');
                jQuery(this).addClass('late');
            }
            else {
                jQuery(this).removeClass('late');
                jQuery(this).addClass('current');
            }
        }
    });
</script>

The warning is only available for testing, and in Chrome and Firefox it returns a date object, but in IE I get NaN.

What is wrong, and how can I do this conversion to make it work in IE too?

+3
source share
5 answers

This question helped me figure out a solution to a problem with which I had conversion dates. I found a way to convert the date without using separate scripts or testing for browser type.

2011-01-01 (, , ).

function convertDate(stringdate)
{
    // Internet Explorer does not like dashes in dates when converting, 
    // so lets use a regular expression to get the year, month, and day 
    var DateRegex = /([^-]*)-([^-]*)-([^-]*)/;
    var DateRegexResult = stringdate.match(DateRegex);
    var DateResult;
    var StringDateResult = "";

    // try creating a new date in a format that both Firefox and Internet Explorer understand
    try
    {
        DateResult = new Date(DateRegexResult[2]+"/"+DateRegexResult[3]+"/"+DateRegexResult[1]);
    } 
    // if there is an error, catch it and try to set the date result using a simple conversion
    catch(err) 
    { 
        DateResult = new Date(stringdate); 
    }

    // format the date properly for viewing
    StringDateResult = (DateResult.getMonth()+1)+"/"+(DateResult.getDate()+1)+"/"+(DateResult.getFullYear());

    return StringDateResult;
}

, !

+6

, , .

var followupDate = new Date(Date.Parse(jQuery(this).text().trim()));

, , , -

jQuery(this).text().trim()

?

+1

: IE, -, , , :

var followupDate = new Date (datestring.replace('-', '/'));

, Firefox, Chrome Firefox, script IE .

+1

, :

var followupdate = new Date(jQuery(this).text().trim().toString());

"toString()" ; Date , IE .

+1

:

new Date(moment(item.ToDate));

Works with Swedish dates also "2013-01-05":

new Date(moment('2013-01-05'));
0
source

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


All Articles