Compare javascript dates! [duplicate]

2

In these two my alert I have two dates, the first date is the date that is taken from my datetime control of devexpress. The second I created a variable and concatenei with get date, month and year.

I'm having trouble comparing what I concatenated with the date of the control because they are in different formats. How to format the date in JavaScript to compare with that first date of the image?

My code:

function ValidaData(controleDataInicio, controleDataFinal) {

    var date = new Date();

    date = (date.getDate() + '/' +  (date.getMonth() + 1) + '/' + date.getFullYear() + ' 00:00:00');

    if (controleDataInicio.GetDate() < date) {

            alert(RetornaInternacionalizacao('AlertaData2'));
            controleDataInicio.SetValue(null);
    }  
}
    
asked by anonymous 10.07.2015 / 16:33

2 answers

4

You can use the MomentJS library to do date operations in javascript.

For example:

if (moment($('[id$=_txtData]').val(), "DD/MM/YYYY").isBefore(Date())) { //regra aqui }

On their website you will find complete documentation for all types of operation, format and regionalization with dates. In my opinion it is the best library to work with dates in javascript, which has always proved problematic with this type of operation.

    
18.02.2016 / 19:09
3

Since you want to make a date comparison, it's not very interesting to put your Date in this format, but rather the opposite. To compare you need to have both dates as Date objects.

The same situation has been addressed here . This component actually returns a strange format.

For this we will take the date that your component returns and transform into a Date object. The Date class constructor does not recognize this string returned by the component but would be able to create a date in the following format "Jan 01 2015". To obtain this format we split the string with the split method and construct a valid string for the constructor. This would be your method:

function ValidaData(controleDataInicio, controleDataFinal) {

    var date = new Date();
    date = (date.getDate() + '/' +  (date.getMonth() + 1) + '/' + date.getFullYear() + ' 00:00:00');
    var dateElements = controleDataInicio.GetDate().split(" ");
    var newDate = new Date(dateElements[1] + " " + dateElements[2] + " " + dateElements[3]);

    if (newDate < date) {

        alert(RetornaInternacionalizacao('AlertaData2'));
        controleDataInicio.SetValue(null);
    }  
}
    
10.07.2015 / 17:38