最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get Last Day of Persian Month + Solution - Stack Overflow

programmeradmin1浏览0评论

after looking web, i cant find any function to do this, i have personal solution that is work. Maybe it will be useful for someone.

**using Moment Plugin to Convert date. ***moment(currentPersianDate).clone().endof('month').format('YYYY/MM/DD') => not Work in Persian Date

  function GetLastDayOfPersianMonth(calendar) {
            const currentDate = new Date();
            const currentPersianDate = moment(currentDate).locale('fa').format('YYYY/M/D');
            const splitDate = currentPersianDate.split("/");
            const year = splitDate[0];
            const month = splitDate[1];
            const lastDayOfPersianMonth = CalculateLeapYear(month, year);
    
            const endPersianMonth = year + "/" + month + "/" + lastDayOfPersianMonth;
        };

    function CalculateLeapYear(month, year) {
            if (month <= 6) {
                return 31;
            }
            if (month > 6 && month < 12) {
                return 30;
            }

            const leapMatch = [1, 5, 9, 13, 17, 22, 26, 30];
            const number = year % 33;
            const isLeap = leapMatch.includes(number);
           
            if (month == 12 && !isLeap) {
                return 29;
            }
            if (month == 12 && isLeap) {
                return 30;
            }
        }

after looking web, i cant find any function to do this, i have personal solution that is work. Maybe it will be useful for someone.

**using Moment Plugin to Convert date. ***moment(currentPersianDate).clone().endof('month').format('YYYY/MM/DD') => not Work in Persian Date

  function GetLastDayOfPersianMonth(calendar) {
            const currentDate = new Date();
            const currentPersianDate = moment(currentDate).locale('fa').format('YYYY/M/D');
            const splitDate = currentPersianDate.split("/");
            const year = splitDate[0];
            const month = splitDate[1];
            const lastDayOfPersianMonth = CalculateLeapYear(month, year);
    
            const endPersianMonth = year + "/" + month + "/" + lastDayOfPersianMonth;
        };

    function CalculateLeapYear(month, year) {
            if (month <= 6) {
                return 31;
            }
            if (month > 6 && month < 12) {
                return 30;
            }

            const leapMatch = [1, 5, 9, 13, 17, 22, 26, 30];
            const number = year % 33;
            const isLeap = leapMatch.includes(number);
           
            if (month == 12 && !isLeap) {
                return 29;
            }
            if (month == 12 && isLeap) {
                return 30;
            }
        }
Share Improve this question edited May 19, 2021 at 15:11 rahman asked May 17, 2021 at 7:08 rahmanrahman 1319 bronze badges 2
  • 2 Hey @rahman. You can answer your own question on StackOverflow. So might I suggest taking the solution part of the above post and moving it into an answer. This way the solution is clearer. Also improve the question by adding more details about it. – Shubham Vasaikar Commented May 17, 2021 at 7:15
  • @rahman See my alternative solution – Mohsen Alyafei Commented Mar 7, 2022 at 11:39
Add a ment  | 

4 Answers 4

Reset to default 3

you can find one day before the first day of next month. for example, if you want to find the last day of the 6th month:

const firstDayOfNextMonth = moment.from('1400/07/01', 'fa', 'YYYY/MM/DD');
const lastDayOfMonth = firstDayOfNextMonth.add(-1,'d');
const lastDayOfMonthPersianDate = lastDayOfMonth.locale('fa').format('YYYY/M/D');

so for last day of current month:

const currentDate = new Date();
const currentPersianDate = moment(currentDate).locale('fa').add(1,'month');
const firstDayOfNextMonthSt = currentPersianDate.format('jYYYY') + '/' + currentPersianDate.format('jM') + '/01';
//and then
const firstDayOfNextMonth = moment.from(firstDayOfNextMonthSt, 'fa', 'YYYY/MM/DD');
const lastDayOfMonth = firstDayOfNextMonth.add(-1,'d');
const lastDayOfMonthPersianDate = lastDayOfMonth.locale('fa').format('YYYY/M/D');

you can write a function like this and use it:

function getLastDayOfMonthPersianDate(firstDayOfNextMonthSt){
    const firstDayOfNextMonth = moment.from(firstDayOfNextMonthSt, 'fa', 'YYYY/MM/DD');
    const lastDayOfMonth = firstDayOfNextMonth.add(-1,'d');
    const lastDayOfMonthPersianDate = lastDayOfMonth.locale('fa').format('YYYY/M/D');

    return lastDayOfMonthPersianDate;
}

see snippet for function usage:

function getLastDayOfMonthPersianDate(firstDayOfNextMonthSt){
    const firstDayOfNextMonth = moment.from(firstDayOfNextMonthSt, 'fa', 'YYYY/MM/DD');
    const lastDayOfMonth = firstDayOfNextMonth.add(-1,'d');
    const lastDayOfMonthPersianDate = lastDayOfMonth.locale('fa').format('YYYY/M/D');
    
    return lastDayOfMonthPersianDate;
}

const lastDayOfMonthPersianDate = getLastDayOfMonthPersianDate('1400/07/01');
console.log('last day of the 6th month');
console.log(lastDayOfMonthPersianDate);
console.log('-------');

const currentDate = new Date();
const currentPersianDate = moment(currentDate).locale('fa').add(1,'month');
const firstDayOfNextMonthSt = currentPersianDate.format('jYYYY') + '/' + currentPersianDate.format('jM') + '/01';
const lastDayOfCurrentMonthPersianDate = getLastDayOfMonthPersianDate(firstDayOfNextMonthSt);
console.log('last day of the current month');
console.log(lastDayOfCurrentMonthPersianDate);
<script src="https://unpkg./jalali-moment/dist/jalali-moment.browser.js"></script>

you can use this code in C# my site https://mohammadhosseinaref.ir

        public static string PersianDayOfWeek(DayOfWeek dayOfWeek)
    {
        switch (dayOfWeek)
        {
            case DayOfWeek.Sunday:
                return "یکشنبه";
            case DayOfWeek.Monday:
                return "دوشنبه";
            case DayOfWeek.Tuesday:
                return "سه شنبه";
            case DayOfWeek.Wednesday:
                return "چهار شنبه";
            case DayOfWeek.Thursday:
                return "پنج شنبه";
            case DayOfWeek.Friday:
                return "جمعه";
            case DayOfWeek.Saturday:
                return "شنبه";
            default:
                return null;
        }
    }

      public static Dictionary<int, string> ListOfPersianDayOfMonth(int month, int years)
    {
        Dictionary<int, string> dicDays = new Dictionary<int, string>();

        PersianCalendar p = new PersianCalendar();

        var dates = Enumerable.Range(1, p.GetDaysInMonth(years, month))
               .Select(day => ParsePersianToGorgian(years + "/" + month + "/" + day))
               .ToList();

        foreach (var item in dates)
        {
            var day = GeorgianToPersian(item.Value, ShowMode.OnlyDate);
            dicDays.Add(int.Parse(day.Split('/')[2]), DayPersian(item.Value.DayOfWeek) + " " + day);
        }
        return dicDays;
    }

Here is an alternative solution without using libraries.

Given a Gregorian Date, the function will return the information about the Persian Month in that Gregorian Date.

The information returned is:

[1] The Persian Day (Number) (1-31) for that date

[2] The Persian Month (String)

[3] The Persian Year (Number)

[4] Total Days in the Persian Month (Number)

[5] The Gregorian Date that the Persian Month starts on (Date object)

[6] The Gregorian Date that the Persian Month ends on (Date object)

/*********************************************************************
* @function      : getPersianMonthInfo(date)
* @purpose       : Returns information on a Persian Month for a given Gregorian Date
* @version       : 1.00
* @author        : Mohsen Alyafei
* @date          : 07 Mar 2022
* @Licence       : MIT
* @param         : {date} a valid Gregorian Date Object
* @returns       : An Array of seven (7) elements with the following data:
*                  [0] The Gregorian Date (the input date) in YYYY-MM-DD format
*                  [1] The Persian Day (Number) for that date
*                  [2] The Persian Month (String)
*                  [3] The Persian Year (Number)
*                  [4] Total Days in the Persian Month (Number)
*                  [5] The Gregorian Date that the Persian Month starts on (Date object)
*                  [6] The Gregorian Date that the Persian Month ends on   (Date object)
**********************************************************************/
function getPersianMonthInfo(date) {
let sD=new Date(date),c='en-u-ca-persian-nu-latn',d=sD,gD=0,tD= 0,pD,n='numeric',
    iDay  =new Intl.DateTimeFormat(c,{day:n}).format(sD),
    iMonth=new Intl.DateTimeFormat(c,{month:'long'}).format(sD),
    iYear =new Intl.DateTimeFormat(c,{year:n}).format(sD).split(" ")[0];
for (let i=0;i<32;i++) {
    pD= new Intl.DateTimeFormat(c,{day:n}).format(d);
    if (+pD>tD) tD=pD,gD++; else break;
    d=new Date(d.setUTCDate(d.getUTCDate()+1));
    }
let gEndT=new Date(sD.setUTCDate(sD.getUTCDate()+gD-2));
return [new Date(date).toISOString().split("T")[0],+iDay,iMonth,+iYear,tD,new Date(gEndT.setUTCDate(gEndT.getUTCDate()-tD+1)),new Date(gEndT)];
}
//==================================================================















//==================================================================
// Test Cases
//==================================================================
output(getPersianMonthInfo(new Date(Date.now()))); // today's date
output(getPersianMonthInfo("2022-04-10"));         // 10 April 2022
//==================================================================


function output([gDate, iDay, iMonth, iYear, tD, gStart, gEnd]) {

console.log(`
Gregorian Date              : ${gDate}
Persian Day                 : ${iDay}
Persian Month               : ${iMonth}
Persian Year                : ${iYear}
Total Days in Persian Month : ${tD}
Persian Month Starts on     : ${gStart}
Persian Month Ends on       : ${gEnd}
`
);
}
//==================

try this code :

public static DateTime MiladiDateTimeOfLastShamsiDayOfMonth(this DateTime value)
{
    PersianCalendar pc = new PersianCalendar();
    var datetime = pc.ToDateTime(pc.GetYear(value), pc.GetMonth(value), pc.GetDaysInMonth(value.Year, value.Month), value.Hour, value.Minute, value.Second, value.Millisecond);
    return datetime;
}

public static string ShamsiDateTimeOfLastShamsiDayOfMonth(this DateTime value, bool withTime = false)
{
    return MiladiToShamsi(MiladiDateTimeOfLastShamsiDayOfMonth(value), withTime);
}

public static string MiladiToShamsi(DateTime dateTime, bool withTime = false)
{
    string ret = "";

    PersianCalendar pc = new PersianCalendar();

    ret = $"{pc.GetYear(dateTime).ToString()}/{pc.GetMonth(dateTime).ToString().PadLeft(2, '0')}/{pc.GetDayOfMonth(dateTime).ToString().PadLeft(2, '0')}";

    if (withTime)
    {
        ret += " " + dateTime.ToString("HH:mm:ss");
    }


    return ret;
}
发布评论

评论列表(0)

  1. 暂无评论