2

I have loaded dates in my code . At this time I cant change my code I mean I will do it when there is any other solution. so would you pleas tell me how can I convert dates to shamsi format? is there any function to for converting date to shamsi format in js??

may codes:

<input type="text" id="number" name="number"><input type="button" value="load" id="btn">
<select id="date" name="date">

</select>

js:

<script>
    $(document).ready(function () {
        $("#btn").click(function () {
            var n=$("#number").val();
            var i;
            var d = new Date();
            for (i=1 ; i<=n ;i++){
//              var b=n;
                $("#date").append("<option>"+d.getFullYear()+"/"+d.getMonth()+"/"+(d.getDate()+i)+"</option>");
            }
        });
    });
</script>

2 Answers2

2

To convert the Gregorian date to jalali in JavaScript you can do the following.

The first method:

new Intl.DateTimeFormat("fa-IR").format(new Date());
new Intl.DateTimeFormat("fa-IR").format('2022/01/31');

The second method:

new Date().toLocaleDateString('fa-IR');

I changed your code, you can test.

$(document).ready(function () {
    $("#btn").click(function () {
        var n=$("#number").val();
        var i;
        const formatOptions = {numberingSystem: 'latn', hourCycle: 'h24', hour12: false};
        var date = new Date().toLocaleDateString('fa-IR', formatOptions);
        var d = date.split('/');
        for (i=1 ; i<=n ;i++){
            $("#date").append("<option>"+d[0]+"/"+d[1]+"/"+(+d[2]+i)+"</option>");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="text" id="number" name="number"><input type="button" value="load" id="btn">
<select id="date" name="date"></select>
Mahdi Saeidi
  • 176
  • 4
1

Shamsi seems to be an exotic calendar format which is not directly supported by JavaScript.

You could take a look at Moment.js and this additional library, moment-jalaali for Moment.js (YMMV: haven't tried this).

AKX
  • 152,115
  • 15
  • 115
  • 172