开发者

Better way to Select & Read Date in dd/mm/yy format?

In earlier vb.net 2008 I used the DateTime to read the date in dd/mm/yy format. I use to change the culture info to UK format. So that the date will be sel开发者_StackOverflow社区ected from SQL server as in dd/mm/yy format.

But I know it's not good to play with CultureInfo. Even though I used like the following manner.

Any other better Ideas for me?

Sub Form_Load()
    Thread.CurrentThread.CurrentCulture = New CultureInfo("en-GB", False)    
End Sub

Any other better Ideas for me? Thanks for the Ideas.

Thanks & Regards.


From DateTime to string:

string s = DateTime.Today.ToString("dd/MM/yyyy");

From string to DateTime:

DateTime d;
bool success = DateTime.TryParseExact("26/05/2011", "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);


In C# you could get the date string in desired format like,

string date = DateTime.Now.ToString("dd/MM/yyyy");

If you want to get DateTime object from string value representing DateTime in specific culture, you can do

     DateTime dt = new DateTime();
                DateTime.TryParse("16/01/2011", System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"),
  System.Globalization.DateTimeStyles.None, out dt);


DateTime --> String

DateTime.Now.ToString( new CultureInfo("fr-FR", false) );

String --> DateTime:

The preferred method would probably be DateTime.Parse()

dateString = "16/02/2008 12:15:12";
try 
{
     dateValue = DateTime.Parse(dateString, new CultureInfo("en-GB", false));
     Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
}   
catch (FormatException) 
{
     Console.WriteLine("Unable to convert '{0}'.", dateString);
}

This way you are not changing the Culture info of the current Context. This does assume you know what the format will be beforehand though.


You can format the date using the CultureInfo, without setting the culture for the whole thread, thanks to the IFormatProvider interface:

DateTime d = DateTime.Now;
CultureInfo c = new CultureInfo("en-GB", false);
string s = d.ToString(c.DateTimeFormat);

This has the added advantage that you don't have any hard-coded formats, and if the user changes the localisation settings on their machine, your application will reflect their preferences.

You can use DateTime.TryParse to parse the date...

string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, out date))
{
    // Parsed correctly
}
else
{
    // Invalid string!
}

And even use an IFormatProvider to help TryParse work out the format.

CultureInfo c = new CultureInfo("en-GB", false);
string s = "01/01/2011";
DateTime date;
if (DateTime.TryParse(s, c.DateTimeFormat, DateTimeStyles.None, out date))
{
    // Parsed correctly
}
else
{
    // Invalid string!
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜