2011-08-31 115 views
-5

我想要得到的日期,例如2011年9月在sql server 2005中的日期,或者在c# 因此结果应该是 4/9/2011 11/9/2011 18/9/2011 25/9/2011如何获取特定年份某月的某一天的日期?

+4

7个问题,不接受,没有投票,也没有尝试自己解决。我在这里看到一个模式... – JNK

+0

也许没有接受,但问题基本上没问题。 –

回答

0

.NET C#

的DateTime DATEVALUE =新日期时间(2008年,6,11); Console.WriteLine((int)dateValue.DayOfWeek); // Displays 3

从MSDN上搜索

0

我真的不明白你想要什么。但我会回答,因为我认为我理解。

弗里斯特所有我们这样做对你的代码: 此代码如果C#

DateTime的时间= DateTime.Now;

string timenow;

你可以这样做 - timenow = time.timeofday.tostring(); 女巫会给我们:21:44:15.3487 或我们可以做 - timenow = time.ToLongDateString(); 它会给我们的日期。

还有Time.ToShortDateString();.

只需要你认为你需要的功能。

在SQL中,你可以使用“GetDate()”。

我想我帮忙,高兴,如果我做了:)

+0

我想要的是在特定年份的某个月份获取所有星期日的日期,就好像你看到9月份有4个星期天一样,2011年4月9日,11/9/2011,18/9/2011,25/9/2011,所以我想在sql server中获得这4个日期 –

2

首先我会使用该月的第一天创建一个DateTime

从那里,我会选DayOfWeek属性,做一些数学(减/添加)来找到匹配你想要的日期的正确日期。

从那里,我会一直呼叫DateTime.AddDays(7),并返回这些值,直到month属性翻转。

我会写一个这样做的函数,需要一年,一个月和一个DayOfWeek。它会返回IEnumerable<DateTime>yield return的每个值。

事情是这样的:

using System; 
using System.Collections.Generic; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     foreach (var date in DayOfWeek.Monday.OccurrencesInMonth(year: 2011, month: 8)) 
     { 
      Console.WriteLine(date); 
     } 
    } 
} 

public static class DayOfWeekExtensions 
{ 
    public static IEnumerable<DateTime> OccurrencesInMonth(this DayOfWeek targetDayOfWeek, int year, int month) 
    { 
     var firstDayInYear = new DateTime(year, month, 1); 
     var currentDay = firstDayInYear.Next(targetDayOfWeek); 

     while (currentDay.Month == month) 
     { 
      yield return currentDay; 
      currentDay = currentDay.AddDays(7); 
     } 
    } 
} 

public static class DateTimeExtensions 
{ 
    public static DateTime Next(this DateTime current, DayOfWeek dayOfWeek) 
    { 
     int offsetToNextOccurrence = dayOfWeek - current.DayOfWeek; 
     if (offsetToNextOccurrence < 0) 
      offsetToNextOccurrence += 7; 
     return current.AddDays(offsetToNextOccurrence); 
    } 
} 

2011年8月1日12:00:00 AM
8/8/2011 12:00:00 AM
2011/8/15 12: 00:00 AM
2011年8月22日12:00:00 AM
2011年8月29日12:00:00 AM

0

你可以尝试这样的事情:

DECLARE @Date DATETIME 
SELECT @Date = '20110801' 

SELECT DATEADD(dd, number, @Date) Date 
FROM master..spt_values 
WHERE YEAR(DATEADD(dd, number, @Date)) = YEAR(@Date) AND MONTH(DATEADD(dd, number, @Date)) = MONTH(@Date) AND DATEPART(dw, DATEADD(dd, number, @Date)) = 1 
     AND [Type] = 'p' 
相关问题