[英]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 我有一个将日期显示为dd / mm / yyyy的数据库在我的列表视图中,我已对其进行了更改,因此它显示为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 我还有另一部分代码,如果日期超过2小时,它将字体颜色更改为红色
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. 但是,这就是上面的代码似乎只能在旧格式dd / mm / yyyy上工作的问题。 So it will highlight 01/11/yyyy but not 01/14/yyyy as it's not recognizing it.
因此它将突出显示01/11 / yyyy,但不会突出显示01/14 / yyyy,因为它无法识别它。 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"))
You can use DateTime.TryParseExact and provide the dateformat you changed to. 您可以使用DateTime.TryParseExact并提供更改为的日期格式。 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
Since you already know the format you want to use you can just use DateTime.TryParseExact instead. 由于您已经知道要使用的格式,因此可以只使用DateTime.TryParseExact。
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)
If your system date format is dd/mm/yyyy, TryParse will try to convert your string into this format. 如果您的系统日期格式为dd / mm / yyyy,TryParse将尝试将您的字符串转换为该格式。
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. 如果您有01/14 / yyyy(根据系统时间无效),则Total不会初始化为您要分析的日期。 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"
“ dd / mm / yyyy”或“ mm / dd / yyyy”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.