我怎样才能改变哪一天是一周的第一天

本文关键字:一周 第一天 一天 能改变 | 更新日期: 2023-09-27 18:10:43

我需要在asp.net中更改一周中的第一天,即我希望周六是一周的第一天。

例如,下面的代码应该在周一返回3:

(int)DateTime.Now.DayOfWeek

我怎样才能改变哪一天是一周的第一天

您不能影响DateTime.DayOfWeek的值,因为这是System.DayOfWeek的一种类型,是枚举(即值是常量(。System.DayOfWeek的定义在下面的代码块中。所以,如果你想把DayOfWeek当作周一和周六的3来对待,那么我必须假设你想要一个基于1到7的编号系统。在这种情况下,您可以使用((int)DateTime.Now.DayOfWeek+1) % 7 + 1来获得所需的数字。如果计算不需要这个,最好只将DateTime.Now.DayOfWeek的值与其枚举常量(例如if( DateTime.Now.DayOfWeek == DayOfWeek.Monday ) ...(进行比较。

// Summary:
//     Specifies the day of the week.
[Serializable]
[ComVisible(true)]
public enum DayOfWeek
{
    // Summary:
    //     Indicates Sunday.
    Sunday = 0,
    //
    // Summary:
    //     Indicates Monday.
    Monday = 1,
    //
    // Summary:
    //     Indicates Tuesday.
    Tuesday = 2,
    //
    // Summary:
    //     Indicates Wednesday.
    Wednesday = 3,
    //
    // Summary:
    //     Indicates Thursday.
    Thursday = 4,
    //
    // Summary:
    //     Indicates Friday.
    Friday = 5,
    //
    // Summary:
    //     Indicates Saturday.
    Saturday = 6,
}

使用以下代码更改asp.net应用程序中的第一天。

CultureInfo _culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
CultureInfo _uiculture = (CultureInfo)CultureInfo.CurrentUICulture.Clone();
_culture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Saturday;
_uiculture.DateTimeFormat.FirstDayOfWeek = DayOfWeek.Saturday;
System.Threading.Thread.CurrentThread.CurrentCulture = _culture;
System.Threading.Thread.CurrentThread.CurrentUICulture = _uiculture;

我想您只需要更改您使用的区域性(DayOfWeek枚举(。

Thread.CurrentThread.CurrentCulture = New CultureInfo("ar-EG")

我创建了这个C#扩展方法,它基于一个替代的第一个工作日返回一个从零开始的索引。

DayOfWeek默认为Sunday=0,Monday=1。。。,星期六=6。我们希望(例如(DayOfWeek是星期一=0,星期二=1。。。,星期日=6。

假设当前工作日为周日:

DateTime.Now.DayOfWeek; // returns Sunday
(int)DateTime.Now.DayOfWeek; // returns 0
DateTime.Now.DayOfWeek(DayOfWeek.Monday); // returns 6    
public static class ExtensionMethods
{
    /// <summary>
    /// Returns an zero-based index where firstDayOfWeek = 0 and lastDayOfWeek = 6
    /// </summary>
    /// <param name="value"></param>
    /// <param name="firstDayOfWeek"></param>
    /// <returns>int between 0 and 6</returns>
    public static int DayOfWeek(this DateTime value, DayOfWeek firstDayOfWeek)
    {
        var idx = 7 + (int)value.DayOfWeek - (int)firstDayOfWeek;
        if (idx > 6) // week ends at 6, because Enum.DayOfWeek is zero-based
        {
            idx -= 7;
        }
        return idx;
    }
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date.DayOfWeek == DayOfWeek.Friday)
            {
                e.Day.IsSelectable = false;
                e.Cell.BackColor = Color.AliceBlue;
            }
        }

它真的很管用。这里的DayRender是一个事件。