如何在C#中获得第一天和最后一天的月份名称?

时间:2013-07-03 13:00:38

标签: c# datetime

我有问题。我希望有一个月的第一天和最后一天。例如,如果我将月份名称作为2012年1月和2012年,它应该给我2012年1月的第一天和2012年1月的最后一天.thnx

5 个答案:

答案 0 :(得分:2)

每月开始编号1,但由于最后一天的编号可能不同,因此您可以使用DateTime.DaysInMonth方法。

  

返回指定月份和年份的天数。

最后一天的名字;

DateTime dt = new DateTime(2012, 1, DateTime.DaysInMonth(2012, 1));
Console.WriteLine(dt.DayOfWeek);

//Tuesday

第一天的名字;

DateTime dt = new DateTime(2012, 1, 1);
Console.WriteLine(dt.DayOfWeek);

//Sunday

这是DEMO

答案 1 :(得分:1)

您可以获取一个月中第一天和最后一天的星期几的枚举值,如下所示:

int month = 1;
DateTime date = new DateTime(2012, month, 1);

DayOfWeek firstDay = date.DayOfWeek;
DayOfWeek lastDay = date.AddMonths(1).AddDays(-1).DayOfWeek;

如果您需要将星期几名称转换为本地化字符串:

string firstDayString = DateTimeFormatInfo.CurrentInfo.GetDayName(firstDay);
string lastDayString = DateTimeFormatInfo.CurrentInfo.GetDayName(lastDay);

如果您需要将本地化的月份名称字符串转换为月份数字:

string monthName = "January";
int monthNumber = DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month;

全部放在一起:

string monthName = "January";
int year = 2012;

int monthNumber = DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture).Month;

DateTime date = new DateTime(year, monthNumber, 1);

DayOfWeek firstDay = date.DayOfWeek;
DayOfWeek lastDay = date.AddMonths(1).AddDays(-1).DayOfWeek;

string firstDayString = DateTimeFormatInfo.CurrentInfo.GetDayName(firstDay);
string lastDayString = DateTimeFormatInfo.CurrentInfo.GetDayName(lastDay);

Console.WriteLine("First day of month = " + firstDayString);
Console.WriteLine("Last day of month = " + lastDayString);

答案 2 :(得分:0)

string month = "January";
int year = 2012;
DateTime firstDay = DateTime.Parse(month + ", 1 " + year, CultureInfo.InvariantCulture);
DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);

答案 3 :(得分:0)

var date = new DateTime(2013, 1, 15);

var nextMonth = date.AddMonths(1);

var firstDay = new DateTime(date.Year, date.Month, 1).DayOfWeek;

var lastDay = new DateTime(nextMonth.Year, nextMonth.Month, 1).AddDays(-1).DayOfWeek;

答案 4 :(得分:0)

使用此代码。

DateTime dateTime = DateTime.Now;
DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
string firstDay = firstDayOfTheMonth.DayOfWeek.ToString();
DateTime lastday = firstDayOfTheMonth.AddMonths(1).AddDays(-1);
string lastdayofMonth = lastday.DayOfWeek.ToString();
相关问题