转换时间戳

编程入门 行业动态 更新时间:2024-10-09 01:18:09
本文介绍了转换时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

转换时间戳

本文发布于:2023-11-22 00:34:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615291.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!