Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hey guys, I have to compare 2 timestamps, but before I do that, I have to put it in a forma C# likes. the time stamp comes in this format 2013-09-27 15:09:02.085 and doing this
C#
string date = "2013-09-27 15:09:02.085 ";
DateTime dt = Convert.ToDateTime(date);

Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour:{3}, Minutes:{4},Sec:{5},", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);


crashes the program, because C# wants it in this format

C#
string date = "2013/09/27 15:09:02.085 ";
DateTime dt = Convert.ToDateTime(date);

Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour:{3}, Minutes:{4},Sec:{5},", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);


Now I know how to get it into that format, but it requires a lot of ugly reformatting through code. So my question is , is there an easier way of getting it into this format 2013/09/27 15:09:02.085 cleanly and with as little code as possible?.

Thank you
Posted

1 solution

You should specify a culture
You can try this:

C#
DateTime.Now.ToString("yyyy/MM/dd h:mm:ss tt", CultureInfo.InvariantCulture)

but perhaps it would be better if you specified a different culture, for instance if you want the US culture:

C#
DateTime.Now.ToString("yyyy/MM/dd h:mm:ss tt", CultureInfo.GetCultureInfo("en-US"))

Both of the above will give you / as a separator
Hope this helps
 
Share this answer
 
v2
Comments
rudolph098 27-Sep-13 16:05pm    
thank you

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