Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,

        I have month & Year ( "March" & "2013" ) how can i find first date and last date of this month and Year. ( Like start date - 03/01/2013  & End date - 03/31/2013 )
Posted

Possible solution could be
C#
DateTime firstDay = new DateTime(2013, 3, 1);
DateTime lastDay = firstDay.AddMonths(1).AddDays(-1);

but there's quite a couple :)

if you like to use a string
C#
var firstDay = DateTime.Parse("1 March 2013");
var lastDay  = firstDay.AddMonths(1).AddDays(-1);
 
Share this answer
 
v2
Comments
FspFriends 2-Mar-13 8:36am    
How can i give this line? DateTime firstDay = new DateTime(2013, 3, 1);

I have only MARCH 2013 both are strings
Espen Harlinn 2-Mar-13 8:40am    
You're kidding aren't you?
StM0n 2-Mar-13 8:57am    
:)
StM0n 2-Mar-13 8:57am    
See my improved answer...
Espen Harlinn 2-Mar-13 9:26am    
5'ed!
Heve a look at: DateTime Constructor (Int32, Int32, Int32)[^] and the DateTime.DaysInMonth Method[^]

DateTime start = new DateTime(2013,3,1);
DateTime end = new DateTime(2013,3,DateTime.DaysInMonth(2013,3));


Best regards
Espen Harlinn
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 12-Mar-13 17:13pm    
Sure, a 5.
—SA
Espen Harlinn 12-Mar-13 17:28pm    
Thank you, Sergey :-D
C#
DateTime firstDateOfMonth = new DateTime(year, month, 1);
DateTime lastDateOfMonth = new DateTime(year, month, DateTime.DaysInMonth(year, month));
 
Share this answer
 
ASP.NET tag checked, so you may need to resolve problem in SQL query. I recommend you to use stored procedure[^], because it can also improves performance:

SQL
CREATE PROCEDURE GetDataByMonthAndYear
        @iMonth INT,
        @iYear INT
AS
BEGIN
    DECLARE @bDate DATETIME
    DECLARE @eData DATETIME

    SET DATEFORMAT ymd;

    SET @bDate = DATEADD(mm, @iMonth-1,DATEADD(yy, @iYear-1900, '1900-01-01'))
    SET @eDate = DATEADD(dd, -1,DATEADD(mm, 1,@bDate))

    --SELECT @bDate AS [bDate], @eDate AS [eDate]

    SELECT Field1, Field2, Field3, FieldN 
    FROM YourTableName
    WHERE [DateField] BETWEEN @bDate AND @eDate

END


On MS SQL Server 2012 you can use DATEFROMPARTS[^] function to build dates from parts.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900