C# 獲取當前是星期幾的方法

happymagic發表於2015-04-24

C#的功能很強大,卻沒有直接提供面向漢字文化的開發傾向

比如我現在要說的獲取當前的星期我提供兩種方法:

①,DateTime.Now.DayOfWeek ,查詢MSDN可以知道該屬性返回的結果是:

//
        // 摘要:
        //     獲取此例項所表示的日期是星期幾。
        //
        // 返回結果:
        //     一個 System.DayOfWeek 列舉常數,它指示星期幾。該屬性值的範圍從零(表示星期日)到六(表示星期六)。
        public DayOfWeek DayOfWeek
        {
            get;
        }

依據這個我們想見該屬性提供了從星期日到星期六的位置,也就是說是列舉,列舉結合陣列不就可以提取我們想要的資料了嗎!程式碼如下:

public string Week()
        {
            string[] weekdays ={ "星期日" ,"星期一" ,"星期二" ,"星期三" ,"星期四" ,"星期五" ,"星期六" };
            string week=weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)];

            return week;
        }

你只要呼叫該方法:Week()就可以得到當前星期幾的漢字表示 Lable1.Text=Week();

②第二種方法是直接根據星期的數目比較小還可以直接轉化,這時候我們可以用switch關鍵字程式碼如下:

public string Week(string weekName)
        {
            string week;
            switch(weekName)
            {
                case "Sunday":
                    week = "星期日";
                    break;
                case "Monday":
                    week = "星期一";
                    break;
                case "Tuesday":
                    week = "星期二";
                    break;
                case "Wednesday":
                    week = "星期三";
                    break;
                case "Thursday":
                    week = "星期四";
                    break;
                case "Friday":
                    week = "星期五";
                    break;
                case "Saturday":
                    week = "星期五";
                    break;
                    return week;
            }
        }

你只要呼叫該方法:Week(DateTime.Now.DayOfWeek)就可以返會漢字的星期幾,Lable1.Text=Week(DateTime.Now.DayOfWeek);

C#中獲取星期幾的中文

System.DateTime.Today.ToString("dddd", new System.Globalization.CultureInfo("zh-CN"));


獲取當前星期幾實現這個功能有多種方法,接下來將列出3種供參考:

string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
string week = Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
lbDay.Text = week; 

lbDay.Text = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek); 

public static string dt;
public static string week;
dt = DateTime.Today.DayOfWeek.ToString();
switch (dt)
{
case "Monday":
week = "星期一";
break;
case "Tuesday":
week = "星期二";
break;
case "Wednesday":
week = "星期三";
break;
case "Thursday":
week = "星期四";
break;
case "Friday":
week = "星期五";
break;
case "Saturday":
week = "星期六";
break;
case "Sunday":
week = "星期日";
break;
}
lbDay.Text = week; 


相關文章