嘿伙计们,我必须比较2个时间戳,但在我这样做之前,我必须把它放在一个形式C#中。时间戳以这种格式出现2013-09-27 15:09:02.085并且这样做
string date = 2013-09-27 15:09:02.085; DateTime dt = Convert.ToDateTime(date); Console.WriteLine( 年份:{0},月份:{1},日:{2},小时:{3},分钟:{4},秒:{5},,dt.Year,dt.Month,dt.Day,dt.Hour,dt.Minute,dt 。第二);使程序崩溃,因为C#想要这种格式
string date = 2013/09/27 15:09:02.085; DateTime dt = Convert.ToDateTime(date); Console.WriteLine( 年份:{0},月份:{1},日:{2},小时:{3},分钟:{4},秒:{5},,dt.Year,dt.Month,dt.Day,dt.Hour,dt.Minute,dt 。第二);现在我知道如何将它变成这种格式,但它需要通过代码进行大量丑陋的重新格式化。所以我的问题是,是否有一种更简单的方法可以使用尽可能少的代码来完成这种格式2013/09/27 15:09:02.085? 谢谢
解决方案你应该指定一种文化 你可以试试这个: DateTime.Now.ToString( yyyy / MM / dd h :mm:ss tt,CultureInfo.InvariantCulture)
但如果您指定不同的文化可能会更好,例如,如果您想要美国文化:
DateTime.Now.ToString( yyyy / MM / dd h:mm:ss tt,CultureInfo.GetCultureInfo( en-US))以上两者都会给你/作为分隔符 希望这有助于
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
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
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
解决方案 You should specify a culture You can try this: 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:
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
更多推荐
转换时间戳
发布评论