根据传递的参数在C#中查找日期 [英] find date in c# based on passed parameters
本文介绍了根据传递的参数在C#中查找日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以年份为整数,即2012年,以月份为文本,即"january"
如何找到上个月的最后一个星期一?
谢谢
Hi,
given the year as int i.e. 2012 and the month as text i.e. "january"
how do I find the last monday of the previous month?
Thanks
推荐答案
类似这样的东西:
Something like this:
FindDate(2012, "January", DayOfWeek.Monday);
public static DateTime FindDate(int year, string month, DayOfWeek day)
{
DateTime lastDay = new DateTime(year, DateTime.ParseExact(month, "MMMM", CultureInfo.CurrentCulture).Month, 1).AddMonths(1).AddDays(-1);
DayOfWeek lastDow = lastDay.DayOfWeek;
int diff = day - lastDow;
return lastDay.AddDays(diff).Date;
}
以下代码可用于查找所需的上个月的最后一天
The following code can be used to find required last day of the previous month
void Main()
{
DateTime date = LastDayOfPreviousMonth(2012, "January", DayOfWeek.Monday);
Console.WriteLine (date);
//date
//26/12/2011
}
public DateTime LastDayOfPreviousMonth(int year, string month, DayOfWeek dayOfWeek){
int monthNo = Array.IndexOf(System.Globalization.CultureInfo
.InvariantCulture.DateTimeFormat.MonthNames, month)+1;
DateTime lastDateOfPrevMonth = new DateTime(year, monthNo,1).AddDays(-1);
return lastDateOfPrevMonth.AddDays(lastDateOfPrevMonth.DayOfWeek < dayOfWeek ?
dayOfWeek - lastDateOfPrevMonth.DayOfWeek - 7 :
dayOfWeek - lastDateOfPrevMonth.DayOfWeek);
}
这篇关于根据传递的参数在C#中查找日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文