penmas penmas - 7 months ago 45
C# Question

How to simply compare if current date is a holiday

I am trying to compare the current date, using DateTime.Now, to a hard-coded list of select holidays to test whether or not the current date is equal to a holiday. I am just getting started with c# so I am not looking for an elegant answer, I am just trying to work with what I have to understand the outcomes.

<script Language="c#" runat="server">
void Page_Load()
DateTime date = DateTime.Now;
dateToday.Text = " " + date.ToString("d");

string newYear = "01/01/2016";
if (newYear == dateTime.Now){
message.Text = ("This is New Years");
<asp:label id="message" runat="server"/>


I would use the DateTime.Date property to compare dates, here's an example

DateTime now = DateTime.Now;
DateTime newYear = new DateTime(2016, 1, 1);
// or DateTime newYear = DateTime.Parse("01/01/2016");

if (newYear.Date == now.Date){
  message.Text = "This is new years";

You are better off using the DateTime structure when dealing with dates, as it conveys more meaning than a string. You also get more flexibility around sorting, filtering, manipulating and displaying the data when you want to do more complex operations. e.g.:

var holidays = new List<DateTime> { new DateTime(2016, 1, 1), new DateTime(2016, 12, 25) };
var now = DateTime.Now;

if (holidays.contains(now.Date){
  message.Text = "Today is a holiday!";