Cory
Cory

Reputation: 161

C# ASP.Net Date Format

I have a database which displays dates as dd/mm/yyyy In my listview I have changed it so it displays as mm/dd/yyyy

<asp:Label ID="TPTIMEIN" runat="Server" Text='<%#Eval("TPTIMEIN", "{0: MM/dd/yyyy HH:mm:ss}") %>' />

I have another part of code which changes the font color to red if the date is more than 2 hours old

Label TimeLabel = (Label)e.Item.FindControl("TPTIMEIN");
            if (TimeLabel != null)
            {

                DateTime Total;
                if (DateTime.TryParse(TimeLabel.Text, out Total) == true)
                {
                    if (Total < DateTime.Now.AddHours(-2))
                    {

                        TimeLabel.ForeColor = System.Drawing.Color.Red;                          
                    }
                }
            }

However, here's the problem the code above only seems to work on the old format dd/mm/yyyy. So it will highlight 01/11/yyyy but not 01/14/yyyy as it's not recognizing it. How would i change this?

Hope this makes sense.....

Edit

I've tried something like this but I can't use a "<" this way

if (Total < DateTime.Now.AddHours(-2).ToString("MM.dd.yyyy"))

Upvotes: 0

Views: 3258

Answers (3)

scartag
scartag

Reputation: 17680

Since you already know the format you want to use you can just use DateTime.TryParseExact instead.

Change

 if (DateTime.TryParse(TimeLabel.Text, out Total) == true)

To

if(DateTime.TryParseExact(TimeLabel.Text,"MM/dd/yyyy HH:mm:ss",null, DateTimeStyles.None, out Total) == true)

Upvotes: 1

Mallikarjuna
Mallikarjuna

Reputation: 130

If your system date format is dd/mm/yyyy, TryParse will try to convert your string into this format.

If you have 01/14/yyyy, which is not valid as per your system time, Total will not be initialized to the date you are parsing. Instead it will initialize to default date time.

please have a consistent date formatting in all places. Either "dd/mm/yyyy" or "mm/dd/yyyy"

Upvotes: 0

Veverke
Veverke

Reputation: 11338

You can use DateTime.TryParseExact and provide the dateformat you changed to. Assuming you changed the format everywhere else in your app.

Example:

   DateTime parsedDateValue;
    string date = "05/14/2014";
    DateTime.TryParseExact(date, "MM/dd/yyyy", Thread.CurrentThread.CurrentCulture, System.Globalization.DateTimeStyles.None, out parsedDateValue);
    Console.WriteLine(parsedDateValue.ToShortDateString());

//prints 5/14/2014

Upvotes: 1

Related Questions