2011-08-31 111 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' 
相關問題