Reputation: 3058
I am having difficulty with different date formats. I am having a web application created using asp.net
c#
. I have used JQuery
Calendar control which shows date along-with time.
I am then parsing this date using DateTime.Parse()
. If the server is set with indian date format then the application generates conversion error "String was not recognized as a valid DateTime."
Is there a way to convert any date format into MM/DD/YYYY
format along with time?
I know i can use DateTime.ParseExact()
but again it will stuck with a particular format.
Any help is greatly appreciated.
Thanks for sharing you wisdom.
Upvotes: 0
Views: 37179
Reputation: 1254
You can use this code.
public static CultureInfo CreateCulture(string shortDateFormat)
{
CultureInfo newCulture = CultureInfo.CreateSpecificCulture("en-US");
newCulture.DateTimeFormat.ShortDatePattern = shortDateFormat;
newCulture.DateTimeFormat.LongDatePattern = shortDateFormat;
return newCulture;
}
Upvotes: 0
Reputation: 3080
string s;
s = dt.ToString("MM-dd-yyyy");
Console.WriteLine(s);//Displays 04-30-2012
Upvotes: 0
Reputation: 354
You can create an Extension methods for this you need to create a static class with static method. It will return you a date format that you define in class
public static class DateExtension
{
public static string GetDateTime(this DateTime? date)
{
if (date.HasValue)
return date.Value.ToString("dd-MMM-yyyy hh:mm tt");
return string.Empty;
}
}
Now in you code you can use this extension for e.g. DateTime.GetDateTime() it will return date with time that with the format you specify in your extension library class
Upvotes: 0
Reputation: 1931
Convert.ToDateTime(DateTime.Now, CultureInfo.GetCultureInfo("en-US")).ToString("MM/dd/yyyy hh:MM:ss");
You can replace en-US by hi-IN for Hindi Date or as per you like. please follow link. for Culture Info.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo(v=vs.80).aspx
If you are unsure of Culture then use below line.
Convert.ToDateTime(DateTime.Now, CultureInfo.CurrentCulture).ToString("MM/dd/yyyy hh:MM:ss");
reference here http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx
Other Method you can use is.
DateTime dt;
DateTime.TryParse(DateTime.Now.ToString(), out dt);
Upvotes: 3
Reputation: 1505
You can try DateTime.Parse or DateTime.TryParse methods
DateTime.Parse(DateTime.Now).ToString("MM/dd/yyyy hh:mm tt");
Also refer
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Thanks
Deepu
Upvotes: 1