1

I am facing one issue fomrating the date

Here is my function

$('input[name="issued_date"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    issued_date: moment().startOf('hour'),
    locale: {
        "format": "YYYY-MM-DD",
        "separator": "-"
    }
});

$('input[name="expiry_date"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    expiry_date: moment().startOf('hour'),
    locale: {
        "format": "YYYY-MM-DD",
        "separator": "-"
    }
});

It showing dates and time in format like this "2019-05-30"

If I change it like this

$('input[name="issued_date"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    issued_date: moment().startOf('hour'),
    locale: {
        "format": "DD-MM-YYYY",
        "separator": "-"
    }
});

$('input[name="expiry_date"]').daterangepicker({
    singleDatePicker: true,
    showDropdowns: true,
    expiry_date: moment().startOf('hour'),
    locale: {
        "format": "DD-MM-YYYY",
        "separator": "-"
    }
});

The format it shows correct.... It will show 05-05-2020 But I am facing one issue in another function .... I need to check the start_date should less than end_date...

So at the time of form submission.... I am returning another function like this

$(".someclass").click(function () {
    $('.loading').show();
    var start_date = document.getElementById('id_issued_date').value;
    var end_date = document.getElementById('id_expiry_date').value;
    if (start_date < end_date)
    {
        var url = "{% url 'add' %}";
        $.ajax({
            type: 'POST',
            url: url,
            data: $("#new_form").serialize(),
            cache: false,
            success: function (data, status) {
                if (data['status'] == "success") {
                   $('#form_modal').modal('hide');
                   toastr.success(data.message);
                   $('#form_modal').children().remove();
                    url = getPathFromUrl(document.location.href)
                    window.location.href = url
                }
                else {
                    $('#form_modal').html(data);
                }
            }
        });
    }
    else{
        toastr.error('start date should be less than End Date');
    }
});

But if I Pass a date like this start date 01/06/2019 and end date is 05/05/2020 it will not work

Actually the start_Date is less than end date

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
Anoop
  • 505
  • 8
  • 23
  • you could use hidden inputs to store the values sent to the server which have the same format and are updated when the ones with the locale specific formats are changed maybe? – akaBase May 07 '20 at 09:27
  • `DD-MM-YYYY` is not a “sortable” date format. You need one that can be compared character-by-character, from left to right - so something like `YYYY-MM-DD` (or without the dashes.) This is using moment.js, I think, so you should be able to use the `format` method that comes with, to get your dates in a sortable format in the place where you need it. – CBroe May 07 '20 at 09:28

3 Answers3

1

Instead of comparing the string representation of the dates using <. Use Moment.js to compare the two values of the date pickers.

The Date Range Picker documentation says the following:

You can access the Date Range Picker object and its functions and properties through data properties of the element you attached it to.

var drp = $('#daterange').data('daterangepicker');

Then use Momenent.js isBefore() to compare the two values:

date1.isBefore(date2)

const $issued_date   = $('input[name="issued_date"]'),
      $expiry_date   = $('input[name="expiry_date"]'),
      $check_dates   = $('button[name="check_dates"]'),
      defaultOptions = {
        singleDatePicker: true,
        showDropdowns:    true,
        locale:           { format: "DD-MM-YYYY", separator: "-" },
      };

$issued_date.daterangepicker(Object.assign({}, defaultOptions, {
  issued_date: moment().startOf('hour'),
}));
$expiry_date.daterangepicker(Object.assign({}, defaultOptions, {
  expiry_date: moment().startOf('hour'),
}));

$check_dates.on("click", () => {
  const issuedDate = $issued_date.data("daterangepicker").startDate,
        expiryDate = $expiry_date.data("daterangepicker").startDate;

  console.log(issuedDate.isBefore(expiryDate));
});
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

<input  type="text" name="issued_date" />
<input  type="text" name="expiry_date" />
<button type="button" name="check_dates">issued_date &lt; expiry_date</button>
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • It's working.... But I am facing one issue...... For Example the same form I am using for edit also .... So in our DB we are storing the date in yyyy-mm-dd format .... if I save start date as 30-05-2019 and save it .... IN edit form it return as 19-052030... – Anoop May 07 '20 at 17:22
  • That seems to be an restriction of the library, it doesn't seem to offer different formatting options for displaying the date and submitting the date. You could add a hidden field, that holds the value in the correct format. Then add an "change" event to the display field and store it in the hidden field correctly formatted. If you have issues working this out or if you want to know different solutions you should ask a new question. – 3limin4t0r May 07 '20 at 21:45
0

create objects of Date and compare.

JavaScript will use the browser's time zone and display a date as a full text string. eg:

let now = new Date()
// now will be equal to Thu May 07 2020 15:08:04 GMT+0530 (India Standard Time)

So, in this case:

    var start_date = document.getElementById('id_issued_date').value;
    var end_date = document.getElementById('id_expiry_date').value;

    let start_date_obj = new Date(start_date);
    let end_date_obj = new Date(end_date); 

    if ( start_date_obj < end_date_obj )
    {
       // do something
    }

you don't have to worry the date format. ie, whether it is in YYYY-MM-DD or DD-MM-YYYY formats or if it has a different seperator. (but should be a date)

Achuth Varghese
  • 2,356
  • 1
  • 4
  • 18
  • It's not working .... Is there any way to convert it using moment.js – Anoop May 07 '20 at 10:34
  • in what format are you getting the value for `document.getElementById('id_issued_date').value;`. It should be a valid date format. – Achuth Varghese May 07 '20 at 10:39
  • let me know what you have tried and why didn't this work. Ok. @David – Achuth Varghese May 07 '20 at 11:36
  • @ AchuthVarghese YOur code is working.... But I am facing one issue...... For Example the same form I am using for edit also .... So in our DB we are storing the date in yyyy-mm-dd format .... if I save start date as 30-05-2019 and save it .... IN edit form it return as 19-052030... – Anoop May 07 '20 at 17:23
  • @David so, you are showing the date in the page as DD-MM-YYYY and want this date to be stored in db. right? You have to convert the date format according to your needs. please see [this](https://stackoverflow.com/questions/27087128/convert-dd-mm-yyyy-to-yyyy-mm-dd-format-using-javascript) – Achuth Varghese May 07 '20 at 17:30
  • In my DB all dates are stored in YYYY-MM-DD , but For users I need to display it in DD-MM-YYYY – Anoop May 07 '20 at 17:41
  • Ok.. then while displaying you have to convert from yyyymmdd to ddmmyyyy OR you can convert it from back end if you want. – Achuth Varghese May 07 '20 at 17:42
  • can we format the date in moment.js right ? Can you help me with that? – Anoop May 07 '20 at 17:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213357/discussion-between-david-and-achuthvarghese). – Anoop May 07 '20 at 17:54
  • @David ok. I'll see you there – Achuth Varghese May 07 '20 at 18:14
0

Hello

Dear

You can try to use this. This is very powerful

today = moment(new Date()).format('YYYY-MM-DD')

You can use any kinds of separator like this

"('YYYY-MM-DD')"
"('YYYY/MM/DD')"
"('YYYY.MM.DD')"
Community
  • 1
  • 1
Masud Rana
  • 590
  • 1
  • 8
  • 17