Compare javascript dates!

Asked

Viewed 745 times

2

In those two of mine Alert I have two dates, the first date is the date that is taken from my devexpress dateedit date control. The second I created a variable and concatenei with get date, Month and year.

I’m having trouble comparing the one I granted with the date of control because they are in different formats. How to format the date in Javascript to compare with that first image date?

inserir a descrição da imagem aqui

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);
    }  
}

2 answers

4

You can use the library Momentjs 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 the 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 been problematic with this type of operation.

3

Since you want to make a comparison between dates it is not very interesting to put your Date in this format but the other way around. To compare you need to have both dates as Date Objects.

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

To do this we will take the date your component returns and transform it into a Date object. The constructor of the Date class does not recognize this string returned by the component but would be able to create a date in the following "Jan 01 2015" format. To get this format we divide the string with the split method and build 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);
    }  
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.