DateTIme help

  • Thread starter Thread starter AVL
  • Start date Start date
A

AVL

Hi,
I've need some info regarding datetime conversions..
I've a string in the below format'"dd/mm/yyyy"..I want it to be converted to
Datetime object with the date format as "mm/dd/yyyy"
I've used the below code..

Dim provider As IFormatProvider
provider = New System.Globalization.CultureInfo("en-US", True)
drnewRow("Inv_Date_Detail") = DateTime.ParseExact("21/11/2007",
"dd/MM/yyyy", provider).ToShortDateString()

This workds fine if my current culture in regional settings is "en-US"..
but fails when I move my current culture to 'en-GB"..

I want a generic solution to this..
how shud i convert a "dd/mm/yyyy" to "mm/dd/yyyy" in vb/net?
 
DateTime objects don't have "formats"... they're just objects with
data. Formatting happens at the moment of generating a string from
the object.

There are two parts to my recommendation:
1. Importing a string into a DateTime object.
2. Displaying a string *from* a DatTime object.

Neither of these suggestions are the "elegant" way. In other words,
I'm not going to use the built in parsing and culture functionality.
I've found that they're difficult to maintain, especially difficult to
test, and somewhat difficult to read.

Instead, in situations like this, I just parse and format the text
myself. I'm guarenteed that this will work, regardless of the culture
settings of the machine. Note that my 1st line assumes an input
string formatted as you say "dd/mm/yyyy".

string[] DateParts = "21/11/2007".split('/');
DateTime MyDate =
new DateTime(
int.Parse(DateParts[2]), //year
int.Parse(DateParts[1]), //month
int.Parse(DateParts[0])); //day
string NewDateString =
MyDate.Month.ToString().PadLeft(2, '0') + '/' +
MyDate.Day.ToString().PadLeft(2, '0') + '/' +
MyDate.Year.ToString();

Hope that helps.
 
[...]
Dim provider As IFormatProvider
provider = New System.Globalization.CultureInfo("en-US", True)
drnewRow("Inv_Date_Detail") = DateTime.ParseExact("21/11/2007",
"dd/MM/yyyy", provider).ToShortDateString()

This workds fine if my current culture in regional settings is "en-US"...
but fails when I move my current culture to 'en-GB"..

How does it fail? What goes wrong?

Using ParseExact() should get you the correct DateTime value from the
original string. So the only thing left is to make sure you provide an
exact format string rather than relying on ToShortDateString() when
converting back to a new string.

If you specifically want the output format to be "mm/dd/yyyy" then provide
that format to DateTime.ToString(). It should give you the output you
want.

Pete
 
Back
Top