How to change the format of date in ASP.NET?
I have two textboxes: TextBox1
, TextBox2
, and a button Button1
.
I want to insert a random date into TextBox1
开发者_JAVA百科 (format -- dd/mm/yyyy) and after clicking the button I want to convert the inserted date into different format (yyyy/mm/dd).
How do I get this behavior?
To parse the date that was set into the first TextBox
:
var parsedDateTime = DateTime.ParseExact(
textBox1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
To set the same date to the second TextBox
, but in different format:
var textBox2.Text = parsedDateTime.ToString("yyyy/MM/dd");
[Edit] As was found out the format is not dd/MM/yyyy
, it is d/M/yyyy
:
var textBox1 = new TextBox { Text = "2/3/2004" };
var parsedDateTime = DateTime.ParseExact(textBox1.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
var textBox2 = new TextBox();
textBox2.Text = parsedDateTime.ToString("yyyy/MM/dd");
Try this. Documented nicely on MSDN.
精彩评论