I have an issue, i have a user based datetime format setting.
Now, i set the input format in the Global.asax as shown below
void MvcApplication_PreRequestHandlerExecute(object sender, EventArgs e)
{
if (userSettings.Settings.ContainsKey(Constants.DateFormat))
{
CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
cultureInfo.DateTimeFormat.DateSeparator = "/";
cultureInfo.DateTimeFormat.FullDateTimePattern = userSettings.Setting.Attributes[Constants.DateFormat];
cultureInfo.DateTimeFormat.LongDatePattern = userSettings.Setting.Attributes[Constants.DateFormat];
cultureInfo.DateTimeFormat.ShortDatePattern = userSettings.Setting.Attributes[Constants.DateFormat];
}
}
But when i bind the date values from a UI textbox to a property, i get only null values. what am i missing in this process.
the date format that the user has given is 'dd/mm/yy'. after MVC model binding is done, the input of '01/11/12' is bound as 11th january 2012.
Kindly suggest the issue and where will the fix be working out.
EDIT
Is it possible only to have month as first in a dateformat string like mm/dd/yy. is it not possible to have dd/mm/yy as a format string.
something like this?
cultureInfo.DateTimeFormat.LongDatePattern = CultureInfo.CreateSpecificCulture("id-ID");
The example is taking culture from Indonesia, we use dd/MM/yyyy format.
Perhaps you should look into a formal date format that can then be localized. We chose to go with ISO 8601 (which is now the default for WebAPI). Then, you can be confident on the client that you are going to read the correct date from the serialized format. However, then you need to localize the time (if needed).
Scott Hanselman has a good write up of the issues.
And this datetime javascript library looks interesting.
Related
I want to show Date and Time in format like (2-13-2014). How would I do it.
Here is My code. I try this but it shows me Date and Time like this (2/13/2014). Please help me
private void buttonSave_Click(object sender, EventArgs e)
{
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd-MM-yyyy";
MessageBox.Show(dateTimePicker1.Value.ToShortDateString());
}
I assume you want to show February 1, 2014 as 2-1-2014, so this code should work
MessageBox.Show(dateTimePicker1.Value.ToString("M-d-yyyy"));
You can also change "M-d-yyyy" to any format you like, see #Dumisani's comment below for the reference.
The Format and CustomFormat of the DateTimePicker only relate to what's displayed in the DateTimePicker. The Value property is a DateTime and has no specific connection to the control. It's a binary value that has no format. If you want to display a DateTime in a particular format then you have to specify that format when you convert it to a string, regardless of where it came from in the first place. If you call ToShortDateString then you're going to use the default short date format for the system.
So this seems like an easy thing to do, but still has me stumped. I want to display a list of strings to my user, based off of a few file's creation dates. So basically, display a list of DateTimes. The challenge is that want to use a custom format (something like 5/6/13 12:01 PM) but I want he date part of that to display differently based on how you have your system displaying the date (ie. a Brit would display that date as 6/5/13).
I thought I could just build two strings (one for date and one for time) and make sure that they date is region-formatted, but there is no default option for 5/6/13 (only 5/6/2013):
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
Next I hoped maybe the DateTime.ToShortDateString() function would work, but it displays as 5/6/2013 as well.
I know I can use a completely custom format like this: DateTime.ToString("M/d/yy h:mm tt") but I don't want to fix the date with the month before the day.
I suppose if I can' figure anything out then I could just build a custom datetime for America and for Europe and then query the OS for what datetime they are displaying in. But that seems really excessive. Any thoughts?
You could retrieve the current ShortDate format from current culture, change it and use it with ToString()
var currentDate = DateTime.Now;
var shortDateFormat = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern;
var newShortDateFormat = shortDateFormat.Replace("yyyy", "yy");
Console.WriteLine(currentDate.ToString(shortDateFormat));
Console.WriteLine(currentDate.ToString(newShortDateFormat));
System.Globalization.CultureInfo implements IFormatProvider, so you can provide a CultureInfo object as a parameter to the ToString method.
MSDN seems to have an example of exactly what you want.
I have a JQuery date picker which puts the date into a textbox in format DD/MM/YYYY.
I am trying to store this in SQL Server 2008 which needs to accept the date as MM/DD/YYYY, how should I format the date to get this to work correctly?
This is the code to add a my parameter to the query, which causes an error as the day and the month are the wrong way round
TextBox fixtureDateTextBox = (TextBox)Master.FindControl("ContentPlaceHolderMenu").FindControl("datepicker");
SqlParameter fixtureDateParam = new SqlParameter("#fixtureDate", fixtureDateTextBox.Text);
Never, ever directly insert input text into a parameter as you're doing - it's the root cause of too many security vulnerabilities and holes. Parse the input into a DateTimeOffset object first (you can also use DateTime, but the Offset is better in general to use) by calling DateTimeOffset.Parse(...), then you can simply add it as a parameter without modifying it.
EDIT: I re-read your question, and realized that while the above isn't wrong, it does miss some important things that address your question. See this for how to configure the date picker to display an alternate date format from what it stores in an alternate field:
EDIT 2:
You'll want to parse your DateTime object using the overload which allows you to pass in an IFormatProvider instance.
See http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx for an example of how to do what you're looking to do. Otherwise, DateTime.Parse('13/3/2013') will fail due to unrecognized format.
DateTime.Parse('13/3/2013', new CultureInfo("en-GB").DateTimeFormat) is what you want to do with the input box.
I agree with the other folks that you should be able to configure the JQuery picker format to begin with, but if you can't, this should do the trick:
TextBox fixtureDateTextBox = (TextBox)Master.FindControl("ContentPlaceHolderMenu").FindControl("datepicker");
DateTime fixtureDate = DateTime.Parse(fixtureDateTextBox.Text, new CultureInfo("en-GB"));
SqlParameter fixtureDateParam = new SqlParameter("#fixtureDate", fixtureDate.ToString(new CultureInfo("en-US"));
Try this:
TextBox fixtureDateTextBox = (TextBox)Master.FindControl("ContentPlaceHolderMenu").FindControl("datepicker");
DateTime date = DateTime.Parse(fixtureDateTextBox.Text);
SqlParameter fixtureDateParam = new SqlParameter("#fixtureDate", date);
Add in the namespaces section: using System.Globalization;
then parse your input date as follows:
string DB_Date = (DateTime.Parse(fixtureDateTextBox.Text)).ToString(new CultureInfo("en-US"));
DateTime UKDate = Convert.ToDateTime(datepicker.Text);<br>
string usDate= UKDate.ToString("dd-MM-yyyy");<br>
SqlParameter fixtureDateParam = new SqlParameter("#fixtureDate", usDate);
I'm having an issue with date/time formats in ASP.NET/C#. I have my SQL Server database set up with a PostDate field set to a type of "datetime". But it's saving the date in a strange format. I added a new row through a form and I got this as the date/time string:
2012-09-28 14:56:48.910
When it gets parsed by JSON.NET it gets even stranger. I get:
2012-09-28T14:56:48.91
The date and time are obviously correct, but how do I set things so that I can parse the date into a human-friendly way? There isn't really any code to post because the date is being added when the row is inserted. I'd like to format this as "Sept. 28, 2012 2:56 pm". How do I do that? Do I need to format the string before or after it's parsed as JSON?
That's not a "strange" format at all. The second form is ISO-8601; the first is ISO-8601 without the T. Considering the strange formats you can get in JSON, it looks like you've been let off pretty lightly!
Serialization formats aren't meant to be user-friendly, particularly - they're meant to be machine-to-machine formats.
I would hope that JSON.NET would give you a DateTime after parsing; it should only be giving you the ISO-8601 format after you've converted back to JSON.
If you've got a DateTime that you want to format for user consumption, there are all kinds of options with standard and custom format strings. Don't forget that you should respect the culture of the user, as far as possible - so make sure you're taking appropriate steps to either set the thread's current culture to be the user's one, or that you're passing the culture explicitly to DateTime.ToString etc.
You can try it in C#:
.ToString("MMM d yyyy, h:mm tt")
I cam trying to convert a datetime to string and back, but making it so that it works for all cultures.
I basically have a Textbox (tbDateTime) and a label (lbDateTime). The label tells the user, in which format the software expects the input of tbDateTime. The input of the Textbox will be used for an MySQL command.
Currently it works like this:
lbDateTime.Text = "DD.MM.YYYY hh:mm:ss"; // I live in germany
DateTime date = Convert.ToDateTime(tbDateTime.Text);
String filter = date.ToString("yyyy-MM-dd HH:mm:ss");
Now my question:
Is it possible to determine the format-string for lbDateTime.Text based on the current culture?
Which format does the Convert.ToDateTime function uses?
I hope you can help me. I have actually no pc here to test different cultures, so I'm very afraid that I make something wrong.
Instead of using the Convert.ToDateTime method you can use the DateTime.Parse or DateTime.ParseExact methods. Both allow you to pass a culture that tells how you expect the date to be formatted.
The DateTime.ParseExact method also allows you to specify the format you expect, so you can parse more or less any format with this method.
Edit:
Regarding Convert.ToDateTime. The documentation says that the current culture is used when parsing: http://msdn.microsoft.com/en-us/library/xhz1w05e.aspx
The current culture can be found using the System.Threading.Thread.CurrentThread.CurrentCulture property.
Edit2:
Oh. You may also want to use DateTime.TryParse and DateTime.TryParseExact if you are unsure whether the given format is invalid.
Edit3:
Lots of edits here... I see that you want to determine the culture string that matches the date the user has entered. There is no general solution that is guaranteed to work here. Say for instance that the user has entered the date 01.02.11. There is no way to be certain if this date is in day.month.year or month.day.year or year.month.day and so on.
The best you can do is to have a list of expected input cultures and start with the most likely and try to parse the date using that. If that fails, you can try the second most likely and so on...
But this is really not recommended. Either give the user an expected format, or better, use a date input box that ensures that you receive the selected date in an appropriate format.
The Convert.ToDateTime method will call DateTime.Parse to parse the string, using the current culture (CultureInfo.Current).
You can specify a culture when parsing the string. Example:
DateTime data = DateTime.Parse(tbDateTime.Text, new CultureInfo("en-GB"));
You can use DateTime.ParseExact (or DateTime.TryParseExact) to parse the string using a custom date format. Example:
DateTime data = DateTime.ParseExact(tbDateTime.Text, "dd'.'MM'.'yyyy HH':'mm':'ss", CultureInfo.InvariantCulture);
Another solution :
// Specify the current language (used in the current system you are working on)
CultureInfo currentCulture = CultureInfo.GetCultureInfo(CultureInfo.CurrentCulture.ToString());
// Specify the language that we need
CultureInfo myLanguage = CultureInfo.GetCultureInfo("en-US");
// Adapt the DateTime here, we will use the current time for this example
DateTime currentDate = DateTime.Now;
// The date in the format that we need
string myDate = DateTime.Parse(currentDate.ToString(), currentCulture).ToString(myLanguage);