转换时间戳 [英] Converting Time Stamp

查看:92
本文介绍了转换时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,我必须比较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


这篇关于转换时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆