Date Format

  • Thread starter Thread starter Bob
  • Start date Start date
B

Bob

Hi,

I need to convert a string into DateTime. I can use Convert.ToDateTime()
however the string can be in different formats like 19700504 or 05041970.
Any ideas?

Thanks
 
Hello Bob,

One of the parameters of .ToDataTime is IFormatProvider where you can specify
the format of your string
See sample in MSDN

B> Hi,
B>
B> I need to convert a string into DateTime. I can use
B> Convert.ToDateTime() however the string can be in different formats
B> like 19700504 or 05041970. Any ideas?
B>
B> Thanks
B>
---
WBR,
Michael Nemtsev :: blog: http://spaces.live.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsch
 
..ToString("YYYYMMDD") or .ToString("MMDDYYYY");

(You might want tolook that up, as I can never remember if capital M is
months or minutes.)
 
Bob said:
Hi,

I need to convert a string into DateTime. I can use Convert.ToDateTime()
however the string can be in different formats like 19700504 or 05041970.
Any ideas?

Thanks
Check out DateTime.ParseExact
You can pass a format string that will be used for parsing the date.
JB
 
Bob,

That wont work with convert, use the datetime.parseexact for that, than you
can tell exact what part of your string is a datetime element.

Cor
 
Thanks for all the posts. DateTime.ParseExact works great however I have a
problem. I get passed different date formats like 19700504 or 05041970.
How can I handle different date formats?

Thanks
 
Thanks for all the posts. DateTime.ParseExact works great however I have
a problem. I get passed different date formats like 19700504 or 05041970.
How can I handle different date formats?

In exactly the same way...

DateTime dtm1 = DateTime.ParseExact("19700504", "yyyyMMdd", null);
DateTime dtm2 = DateTime.ParseExact("05041970", "MMddyyyy", null);
 
Bob said:
Thanks for all the posts. DateTime.ParseExact works great however I
have a problem. I get passed different date formats like 19700504 or
05041970. How can I handle different date formats?

Thanks

Since you can get in data with either form, you are going to have to
validate it yourself.
quick and dirty way (assuming you are looking at recent dates and not
historical dates)

- convert the first two characters to an integer.
- if it is greater than 12 then the year is first
string date = "19700504";
int x = Convert.ToInt32(date.Substring(0,2));
if (x > 12)
Console.WriteLine("{0} is in yyyyMMdd format", date);
else
Console.WriteLine("{0} is in MMddyyyy format", date);

Bill
 
Back
Top