Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
What is the difference between

a. String.Format("{0:g}",dt);

VS.

b. DateTime x;
x.Tostring("g");

which one to use in case of multi-culture functionality. I dont want to hard code due to multi-culture functionality.

MM/DD/YYYY HH:MM AM or PM


I Googled and searched msdn however still not clear.
Posted

There isn't any difference. String.Format("{0:g}", dt) will actually call dt.ToString("g")

DateTime implements the IFormattable[^] interface, and String.Format will end up calling the IFormattable.ToString[^] method.
 
Share this answer
 
v2
Comments
Sriram Bala 13-Jan-14 8:16am    
Hi Mo, Thanks for your response, In dt.Tostring() I can pass the cultureInfo.currentculture or Invarientculture... how this works with String.Format("{0:g}",dt)
Maarten Kools 13-Jan-14 8:18am    
There is also a String.Format[^] method which allows you to pass a IFormatProvider.
Sriram Bala 13-Jan-14 8:42am    
Hi I tried this program,
class Program
{
static void Main()
{
DateTime dt = DateTime.Today;
Console.WriteLine(string.Format("{0:g}", dt));
Console.ReadLine();
Console.WriteLine(dt.ToString(CultureInfo.CurrentCulture));
Console.ReadLine();
Console.WriteLine(dt.ToString(CultureInfo.InvariantCulture));
Console.ReadLine();
}
}
I got the output as
1/13/2014 12:00 AM
1/13/2014 12:00:00 AM
01/13/2014 00:00:00
if string.format and .Tostring("g")
is same then the output is different. Am I missing something here? Sorry to ask again and again.
Maarten Kools 13-Jan-14 8:50am    
String.Format("{0:g}", dt) is the same as dt.ToString("g"). That's not the same as dt.ToString(CultureInfo.CurrentCulture). You'll be looking for dt.ToString("g", CultureInfo.CurrentCulture)
Sriram Bala 13-Jan-14 8:47am    
Thanks Mo. I think i am clear now.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900