Home > OS >  How to use Moments.js to change date format from mm/dd/yyyy to dd/mm/yyyy
How to use Moments.js to change date format from mm/dd/yyyy to dd/mm/yyyy

Time:09-13

I'm working on a project using a PHP and AJAX -JQUERY, but I'm facing an issue,i have a dropdown menu that contains the age ranges that's depend on the date typed in birth-date field, the issue is that when i change datepicker format to dd/mm/yyyy the fuction dont work maybe i'm missing somthing, so how to use Moments.js to change date format from mm/dd/yyyy to dd/mm/yyyy, welcome to any suggestion, any help will be appreciated.

here is my code

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div >

    <label for="birth-date" >BIRTH DATE</label>
    <input type="date"   name="birth-date" id="birth-date" >
    <br />
    <label for="date_range" >AGE RANGE</label>
    <select  name="date_range" id="date_range">
        <option></option>
        <option value="1">- 18</option>
        <option value="2">btw 18 25</option>
        <option value="3">btw 25 50</option>
        <option value="4">50 </option>
    </select>
    
</div> 

// Datepicker

$('.datepicker').datepicker({
    format: 'dd/mm/yyyy',
    language: 'fr'
 });

//main function work's but dateformat is mm/dd/yyyy

const getAge = (dob) => { 
return ~~((new Date()-new Date(dob))/(31556952000));
};

$('#birth-date').change(function() {
    const date = $(this).val();
    const age = getAge(date);
    if(age < 18)
       $('#date_range').val(1).change();
    else if(age >= 18 && age < 25)
       $('#date_range').val(2).change();
    else if(age >= 25 && age < 50)
       $('#date_range').val(3).change();
    else
       $('#date_range').val(4).change();
});

//what i have tried but didn't work

const getAge = (dob) => {
const date = moment(dob, 'dd/mm/yyyy');
return moment().diff(date, 'years');
};
$('#birth-date').change(function() {
        const date = $(this).val();
        const age = getAge(date);
        if(age < 18)
           $('#date_range').val(1).change();
        else if(age >= 18 && age < 25)
           $('#date_range').val(2).change();
        else if(age >= 25 && age < 50)
           $('#date_range').val(3).change();
        else
           $('#date_range').val(4).change();
    });

Best regards.

CodePudding user response:

You should use format() method to convert it.

const convertedFormat = moment(dob, 'mm/dd/yyyy').format('dd/mm/yyyy');

OR

const convertedFormat = moment(dob).format('dd/mm/yyyy');

NOTE: I recommend you stop using Moment.js (Why?) and use date-fns.

CodePudding user response:

I just changed this :

const date = moment(dob, 'dd/mm/yyyy');

to :

const date = moment(dob, 'DD/MM/YYYY');
  • Related