i have a query string with format MM/DD/YYYY
I am using it in c# like
DateTime d = Request.QueryString["dateTime"].toString();
its giving me a lot of error saying the date time format is not recognized. If i manually change the datetime in browser address bar (query string) to dd/mm/yyyy then the program just works fine.
I cannot change the query string, is there a way in c# to get it from browser and then convert into date like dd/mm/yyyy please?
edit: the q开发者_StackOverflow中文版uery string:
http://localhost:49543/HM/Admin/ViewDetails.aspx?OrderNo=10&DateCreated=08/30/2010
so you can see the datecreated part is in MM/DD/YYYY format. I am not able to grab it from c#. If I manually change that to 30/08/2010, it works
DateTime d = DateTime.ParseExact(Request.QueryString["dateTime"], "dd/MM/yyyy", CultureInfo.InvariantCulture);
How to turn string from request into DateTime
:
DateTime d = DateTime.ParseExact(Request.QueryString["dateTime"], "dd/MM/yyyy", null);
DateTime.ParseExact is the solution you seek for. But I recommend you to validate the querystring data with a function as follows:
bool isValidDate(string dtStr) {
string pattern = @"^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$)";
System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(pattern);
return re.IsMatch(dtStr);
}
EDIT 1: Besides ParseExact, you can use the following:
DateTime.Parse(dateString, new System.Globalization.CultureInfo("tr-TR"))
Turkish datetime format is dd/MM/YYYY.
// Parsing:
DateTime d = DateTime.Parse(Request.QueryString["dateTime"].toString());
// Conversion:
string dString = d.ToWhateverFormatYouWant();
And here's some info on formatting dates:
http://msdn.microsoft.com/en-us/library/az4se3k1(VS.71).aspx
DateTime.TryParse could be a great option..
Try this it should work
DateTime d =
DateTime.ParseExact(Request.QueryString["dateTime"],
"dd'/'MM'/'yyyy",
CultureInfo.InvariantCulture);
I faced something similar: DateTime Format in C#
You can use: DateTime.Now.ToString("dd/MM/yyyy");
精彩评论