[英]Date conversion ( c#,Asp.net MVC)
我正在嘗試在asp.net mvc Web應用程序上轉換DateTime的格式。
我有這個代碼:
date = Request["date"].AsDateTime().ToString("MM-dd-yyyy HH:mm:ss");
當Request [“ date”]僅一天中的一位數字時,該代碼將非常有效
(例如2016年8月3日),但是當日期有兩位數字時(例如15-03-2016),
它返回01-01-0001 ...有人可以向我解釋原因,並告訴我如何使其更好嗎?
提前致謝 !
編輯:
我正在使用的更多代碼:
用於日期選擇的Javascript日期選擇器:
<script>
$(document).ready(function() {
$('.date').datepicker({ dateFormat: "dd/mm/yy" });
});
</script>
格式代碼:
String date = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 0, 0, 0).ToString("dd/MM/yyyy HH:mm:ss");
string[] formats = { "dd-MM-yyyy" };
DateTime resultDate = new DateTime();
if (DateTime.TryParseExact(Request["date"], formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out resultDate))
{
//if everything good you will have your date in resultDate variable
date = resultDate.ToString("MM-dd-yyyy HH:mm:ss");
}
.AsDateTime()
使用當前機器文化的方法(取決於您的應用程序App.Config
或Web.Config
)。
如果您100%確定您的日期采用dd-MM-yyyy
格式,則可以按照以下方法進行處理:
DateTime.ParseExact(Request["date"], "dd-MM-yyyy", CultureInfo.InvariantCulture)
.ToString("MM-dd-yyyy HH:mm:ss");
正如Stephen Muecle所提到的,最好使用DateTime.TryParseExact()
方法:
//here you can define more that one format to parce
string[] formats = { "dd-MM-yyyy"};
DateTime resultDate = new DateTime();
if (DateTime.TryParseExact(Request["date"], formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out resultDate))
{
//if everything good you will have your date in resultDate variable
date = resultDate.ToString("MM-dd-yyyy HH:mm:ss");
}
else
{
//here the logic if parce fails
}
好的,因為Panagiotis Kanavos的想法,對文化進行硬編碼不是一個好主意。 如果您想做正確的事,則應該應對全球化。
在您的Web.Config
您應該設置uiCulture
和culture
:
<globalization uiCulture="en-GB" culture="en-GB" />
然后,當您初始化jquery ui datepicker時,應設置當前區域性。 像這樣:
$('.datepicker').datepicker({ dateFormat: '@System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern' });
如果您在Web.Config
設置全球化,則您的Whoul應用程序Culture將被同步,甚至可以使用.AsDateTime()
。
嘗試這個:
DateTime unformattedDate;
if(DateTime.TryParse(Request["date"], out unformattedDate)
{
DateTime formattedDate = unformattedDate.ToString("MM-dd-yyyy HH:mm:ss");
}
嘗試使用此:
DateTime date = new DateTime();
date = (DateTime)Request["date"];
String myDate=date.ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.