Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first and last day of the current month

Tags:

date

c#

I have here 2 datepicker for start date and end date.

how can I get the first day and last day of the current month

rdpStartDate.SelectedDate = DateTime.Now;
rdpEndDate.SelectedDate = DateTime.Now;
like image 873
user1647667 Avatar asked Feb 21 '14 01:02

user1647667


People also ask

How do I find the first and last date of the current month?

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied! const now = new Date(); const firstDay = new Date(now.

How do I get the first day of my current month?

1. First day of current month: select DATEADD(mm, DATEDIFF(m,0,GETDATE()),0): in this we have taken out the difference between the months from 0 to current date and then add the difference in 0 this will return the first day of current month.


5 Answers

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
like image 116
Chris Shao Avatar answered Nov 15 '22 14:11

Chris Shao


var now = DateTime.Now;
var first = new DateTime(now.Year, now.Month, 1);
var last = first.AddMonths(1).AddDays(-1);

You could also use DateTime.DaysInMonth method:

var last = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));
like image 29
MarcinJuraszek Avatar answered Nov 15 '22 14:11

MarcinJuraszek


var myDate = DateTime.Now;
var startOfMonth = new DateTime(myDate.Year, myDate.Month, 1);
var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1);

That should give you what you need.

like image 38
TyCobb Avatar answered Nov 15 '22 14:11

TyCobb


Try this code it is already built in c#

int lastDay = DateTime.DaysInMonth (2014, 2);

and the first day is always 1.

Good Luck!

like image 42
Jade Avatar answered Nov 15 '22 16:11

Jade


An alternative way is to use DateTime.DaysInMonth to get the number of days in the current month as suggested by @Jade

Since we know the first day of the month will always 1 we can use it as default for the first day with the current Month & year as current.year,current.Month,1.

var now = DateTime.Now; // get the current DateTime 

//Get the number of days in the current month
int daysInMonth = DateTime.DaysInMonth (now.Year, now.Month); 
    
//First day of the month is always 1
var firstDay = new DateTime(now.Year,now.Month,1); 
    
//Last day will be similar to the number of days calculated above
var lastDay = new DateTime(now.Year,now.Month,daysInMonth);

//So
rdpStartDate.SelectedDate = firstDay;
rdpEndDate.SelectedDate = lastDay; 
like image 43
Vinod Srivastav Avatar answered Nov 15 '22 14:11

Vinod Srivastav