formatting TextBox.Text with ToString(IFormatProvider)

  • Thread starter Thread starter Andy B
  • Start date Start date
A

Andy B

I need to take the value of a textbox and format it in a more readable date.
How do you do this? I tried textbox.text.tostring("date format string") but
the compiler doesnt like that idea... any ideas?
 
Andy B said:
I need to take the value of a textbox and format it in a more readable
date. How do you do this? I tried textbox.text.tostring("date format
string") but the compiler doesnt like that idea... any ideas?

A bit dirty, but you could cast it to a date and then format it, e.g.

VB:
CDate(TextBox1.Text).ToString("dd/MM/yyyy")

C#:
((DateTime)(TextBox1.Text)).ToString("dd/MM/yyyy");
 
C#:
((DateTime)(TextBox1.Text)).ToString("dd/MM/yyyy");

The above format will result in an ambiguous date, e.g. 03/02/2008

Use "dd MMM yyyy" for guaranteed clarity...
 
Hi... Good idea but when I tried the following line of code I ended up with
this: Compiler Error Message: CS0030: Cannot convert type 'string' to
'System.DateTime'
My line of code was:
ConfirmStartTimeLabel.Text=((DateTime)(StartTimeTextBox.Text)).ToString("dddd,
MMMM d yyyy h:mmtt");



All i need to do is take a string that looks like this: 01/01/2008 12:00 PM
and format it to look like a better date. I have the date format strings I
want already...it's just figuring out how to format the string that way
since it isn't actually a date.
 
Andy B said:
Hi... Good idea but when I tried the following line of code I ended up
with this: Compiler Error Message: CS0030: Cannot convert type 'string' to
'System.DateTime'
My line of code was:
ConfirmStartTimeLabel.Text=((DateTime)(StartTimeTextBox.Text)).ToString("dddd,
MMMM d yyyy h:mmtt");



All i need to do is take a string that looks like this: 01/01/2008 12:00
PM and format it to look like a better date. I have the date format
strings I want already...it's just figuring out how to format the string
that way since it isn't actually a date.

So convert it to a date then format the date to a string. That's what Leon
was getting at, but you can't just cast a string to a DateTime, you have to
convert it:

Convert.ToDateTime(TextBox1.Text).ToString("date format");
 
When I tried this idea, it worked until i applied date formatting. the
string 03/12/2008 3:30PM actually turned out as January 01 00000000
12000AM... any ideas?
 
Works for me.

using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s = "03/12/2008 3:30PM";
Console.WriteLine(Convert.ToDateTime(s).ToString("dddd, MMMM d yyyy
h:mmtt"));
}
}
}

If you're still having problems, it's probably related to parsing the string
to a DateTime using whatever your current culture happens to be.
 
Back
Top