using System;
using System.Data.SqlTypes;
using System.Globalization;

//by Erfan Zidehsaraei
public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString ToShamsi(DateTime dt)
    {
        string result = string.Empty;

        if (dt != null)
        {
            PersianCalendar objPersianCalendar = new PersianCalendar();
            //-----------------------------------------------------------------------------------------------------------------------------
            int year = objPersianCalendar.GetYear(dt);
            int month = objPersianCalendar.GetMonth(dt);
            int day = objPersianCalendar.GetDayOfMonth(dt);
            //-----------------------------------------------------------------------------------------------------------------------------
            result = year.ToString().PadLeft(4, '0') + "/" + month.ToString().PadLeft(2, '0') + "/" + day.ToString().PadLeft(2, '0');
        }
        return new SqlString(result);
    }

    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString ToMiladi(string dt)
    {
        string result = string.Empty;

        if (dt != null)
        {
            PersianCalendar objPersianCalendar = new PersianCalendar();
            //-------------------------------------------------------------------------------
            int year = int.Parse(dt.Substring(0, 4));
            int month = int.Parse(dt.Substring(5, 2));
            int day = int.Parse(dt.Substring(8, 2));
            //-------------------------------------------------------------------------------
            result = objPersianCalendar.ToDateTime(year, month, day, 0, 0, 0, 0).ToString("yyyy/MM/dd");
        }
        return new SqlString(result);
    }
}