我有个问题。我想要某个月份的第一天和最后一天名称。例如,如果我将月份名称传递为 2012 年 1 月和 2012 年,它应该给我 2012 年 1 月的第一天和 2012 年 1 月的最后一天。thnx
问问题
1434 次
5 回答
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。
于 2013-07-03T13:07:56.483 回答
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);
于 2013-07-03T13:06:00.077 回答
0
string month = "January";
int year = 2012;
DateTime firstDay = DateTime.Parse(month + ", 1 " + year, CultureInfo.InvariantCulture);
DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);
于 2013-07-03T13:06:12.613 回答
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;
于 2013-07-03T13:06:56.450 回答
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();
于 2013-07-03T13:14:02.733 回答