I have a form on my web site that is going to be dates that the user can enter. What I’d like to do is to convert it after they enter it and store that as a variable.
Currently the way that they are able to enter the date is mm/dd/yyyy and I’d like them to enter it yyyy/mm/dd. How can I reformat that data?
Thank you
Doug
string dts = DateTime.ParseCOLOR=#000000.[/COLOR]ToStringCOLOR=#000000;[/COLOR]
Jake and Serena,
Thank you both for the information.
Serena in your code I’m assuming dts is a variable that I’d declared earlier as a string?
Basically. It depends on what system type you actually want. I converted from string back to string, but you could leave it as a DateTime is your backend stores it like that.
Parse takes any proper date format and creates a DateTime object from it. We then take that result and use ToString, which takes a format for output. Nice and simple.
So if you want to set a label on postback.
if (IsPostBack)
{
myLabel.Text = DateTime.Parse(dateTimeInput.Text).ToString(“yyyy/mm/dd”);
}
If they input any recognised date, it’ll spit it back out the way you want it. They could input “January 3, 2009” and get back “2009/01/03”.
Serena,
would this go in my asp.net page or in the vb.net that I’m using? I’m using .net for essentially the visual aspect of the page, but using vb.net for all the mechanical aspects of the page (like executing my queries, the load events, etc etc.)
That’s up to you and how you’ve assembled things. I’m not privy to that so I really can’t answer that question. Just know that you can put the basic conversion code anywhere you want and use the result as you wish. Personally, I’d create a utility class with this method in it.
public string ConvertDate(string existing)
{
return DateTime.Parse(existing).ToString(“yyyy/mm/dd”);
}
You could even grab the format from an app setting instead of a hard coded value. In addition, you might want to use TryParse or wrap the code in a try-catch block of your own, as it will generate an error if the input is not a recognised date.
That code goes in the code behind page. Force the user to input in the correct format then use DateTime.parse. Use javascript to force format.