Converting any date format in MM/DD/YYYY format - asp.net

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.

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);

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

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

string s;
s = dt.ToString("MM-dd-yyyy");
Console.WriteLine(s);//Displays 04-30-2012

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;
}

Related

Convert DateTime with a specified language

I am coding a MVC 5 internet application and am wanting to convert a DateTime to be displayed as a LocalTime where I have the language. This is for an Azure website.
Here is my code:
DateTime dateTimeUtcNow = DateTime.UtcNow;
DateTime convertedDate = DateTime.SpecifyKind(dateTimeUtcNow, DateTimeKind.Utc);
DateTime dateTimeLocalTime = convertedDate.ToLocalTime();
return dateTimeLocalTime.ToString(new CultureInfo("en-NZ"));
The output from the above code is the exact same output as if I return the DateTime in UTC with no language culture specified.
How can I convert a DateTime in UTC for a local time where I have the culture language?
Thanks in advance.
You can use the second argument to the toString function and use any language/culture you need...
You can use the "d" format instead of ToShortDateString according to MSDN...
So basically something like this to return as NewZ ealand English:
CultureInfo enAU = new CultureInfo("en-NZ");
dt.ToString("d", enAU);
you could modify your method to include the language and culture as a parameter
public static string ConvertDateTimeToDate(string dateTimeString, String langCulture) {
CultureInfo culture = new CultureInfo(langCulture);
DateTime dt = DateTime.MinValue;
if (DateTime.TryParse(dateTimeString, out dt))
{
return dt.ToString("d",culture);
}
return dateTimeString;
}
You may also want to look at the overloaded tryParse method if you need to parse the string against a particular language/culture...

Binding time values to asp.net GridView

I need to bind time values to my gridview. For example, if the time is 13:00, I need to display it as 13-00 in the grid. But it displays as 01-00. How do I resolve this?
You can use GridView.RowDataBound Event to achieve it. Format your time string as you want and assign to to the grid view cell.
You can use date formats to convert datetime into 24-hrs format.
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Text = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
}
}
You need to convert the value into 24-hour format (for instance by selecting a different culture for your application) or simply create some converter class that will convert this for you. There are multiple resources to learn from.
Something like this should work:
DateTime localTime = DateTime.Now;
// 24 hour format -- use 'H' or 'HH'
string timeString24Hour = localTime.ToString("HH:mm", CultureInfo.CurrentCulture);
Taken from another answer here in SO Convert AM/PM time to 24 hours format?
If your culture uses 12-hour format, use a different culture info for the parsing that supports 24-hour format.
Of course you'd probably like to wrap this in a getter property so it will be available for the binding
public string DateIn24HourFormat
{
get
{
return MyConvertFunction(this.Time);
}
}
You get the idea.
Give your Time format in DataFormatString property in BoundColumn.
Apply format as
{0:HH-mm}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspx

showing DateTime in simple format?

i have a column in my database that stores DateTime, now i want to show time in simple format,
you know it will appear like : 12/26/2011 9:39:55 PM
but i want to show it in persian.
When you want to format the DateTime in your application, you need to use a DateTime.ToString overload.
Select the appropriate standard Date and Time format string - in this case "g" looks like a good fit.
If you have not set up your webserver to use the fa-IR culture by default, you will need to pass this culture in as well.
string farsiDate = myDateTime.ToString("g", CultureInfo.GetCultureInfo("fa-IR");
Have a look at the examples on MSDN for using the PersianCalendar class.
var cal = new PersianCalendar();
var today = DateTime.Now;
var persianDate = string.Format("{0}/{1}/{2}",
cal.GetDayOfMonth(today),
cal.GetMonth(today),
cal.GetYear(today));

Convert string date to system datetime in C#

I want to convert string date to system datetime in C#. The user enters date through textbox and it should be converted as to datetime. I trid following code but its not working...
DateTime ToDate = Convert.ToDateTime(txtToDate.Text);
DateTime FromDate = DateTime.Parse(txtFromDate.Text);
It shows the following exception
"String was not recognized as a valid DateTime."
How to do this...???
You could use DateTime.ParseExact(). That way you can specify the format of the input string, so it will be parsed correctly, for example:
dateString = "Sun 15 Jun 2008";
format = "ddd dd MMM yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
whatever user enters in your textbox that should be in valid date format, otherwise write your own function to make it in valid format. then Convert it into DateTime format .
for different format you can check this :
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
for more help you can check similar question on this site :
Validate a DateTime in C#
You can of course parse the user's input and rely on the users to always enter a correct date. But I'd recommend to use a specific control for entering a date, such as the calendar control of the ajax control toolkit.
By using such a control, you can prevent invalid input and it's also much easier for the user. If you search for DatePicker or similar, I'm sure you can find lot's of other similar controls.
Ask the user to enter his datetime in a particular format into textbox i.e., either "ddMMyyyyhhmmss" or "dd/MM/yyyy hh:mm:ss tt" or "dd-MM-yyyy hh:mm:ss tt" or some other formats and use the help of following code to convert in to a Valid datetime.
DateTime ToDate = DateTime.ParseExact(txtToDate.Text, <User DateTime format as String>,
System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Instead, if the above coding makes complicated then you can try DateTime.TryParse() also
First of all you have to validate text box value that it is valid or not, you can use ajax MaskeditExtender control for that and restrict the use enter only require date formate.
DateTime dt = Convert.ToDateTime(date);
here date is in string.

ExtJs 4 Displaying WCF DateTime

I can't figure out how convert the datetime that wcf outputs into a datetime that ExtJs can use. I have found lots of articles about this but they are all for ExtJs 3 and I couldn't get it to work with 4.
I did find this code but I don't know how I could use it to convert everything in my JsonStore.
//this method is used to convert the MS JSON date format to the ExtJS Grid Date Column Value
function dateFormatter(dt) {
/// <summary>this method is used to convert the MS JSON date format to the ExtJS Grid Date Column Value</summary>
/// <param name="dt">Actual JSON Date Value</param>
try {
//microsoft JSON date format needs to convert into Javascript date
var newdata = dt.replace(/\/Date\((-?[0-9]+)([+-][0-9]+)?\)\//g, "new Date($1)");
newdata = eval('(' + newdata + ')');
return newdata.format('m/d/Y');
}
catch (e) {
return dt;
}
}
Unlike Ext JS 3, Ext JS 4 does not extend the native Date object. Instead it provides Ext.Date. So instead of:
date.format('m/d/Y');
you would instead use:
Ext.Date.format(date, 'm/d/Y');
Additionally using eval() is a really bad idea most of the time. This code is no exception.
And if you drop eval, the try-catch is also not needed.
Finally, a function that both parses a date and converts it to another format seems to be doing too much. Often you will want to display the same date in different formats in different parts of your app. Therefore I would rather just have a function that parses the WCF date format into JavaScript Data object. And then use convert the Date object into particular string format at the very place where it's needed.
Removing all extraneous stuff, this is what I get:
function parseWcfDate(dt) {
var milliseconds = dt.replace(/\/Date\((-?[0-9]+)([+-][0-9]+)?\)\//, "$1");
return new Date(parseInt(milliseconds, 10));
}
Anyway, all this is too much trouble... Ext JS has built-in support for parsing WCF formatted dates:
Ext.Date.parse("/Date(1234567894560)/", "MS");
Also see:
How to handle json DateTime returned from WCF Data Services (OData)
How do I format a Microsoft JSON date?
Use JSON.NET with JavaScriptDateConverter.

Resources