C# 如何将刻度转换为日期格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1489243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert ticks to a date format?
提问by user175084
I am converting a ticks value to a date like this:
我正在将刻度值转换为这样的日期:
Convert(datetime, (MachineGroups.TimeAdded - 599266080000000000)/864000000000);
Using this i get:
使用这个我得到:
9/27/2009 10:50:27 PM
But I want just the date in this format:
但我只想要这种格式的日期:
October 1, 2009
My sample ticks value is
我的示例刻度值是
633896886277130000
What is the best way to do this?
做这个的最好方式是什么?
回答by Eric J.
It's much simpler to do this:
这样做要简单得多:
DateTime dt = new DateTime(633896886277130000);
Which gives
这使
dt.ToString() ==> "9/27/2009 10:50:27 PM"
You can format this any way you want by using dt.ToString(MyFormat)
. Refer to this referencefor format strings. "MMMM dd, yyyy"
works for what you specified in the question.
您可以使用dt.ToString(MyFormat)
. 请参阅此参考以了解格式字符串。"MMMM dd, yyyy"
适用于您在问题中指定的内容。
Not sure where you get October 1.
不确定 10 月 1 日在哪里。
回答by Jason Berkan
A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:
可以使用特定的刻度值构造 DateTime 对象。确定刻度值后,您可以执行以下操作:
DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");
回答by JosephStyons
private void button1_Click(object sender, EventArgs e)
{
long myTicks = 633896886277130000;
DateTime dtime = new DateTime(myTicks);
MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
}
Gives
给
September 27, 2009
Is that what you need?
那是你需要的吗?
I don't see how that format is necessarily easy to work with in SQL queries, though.
不过,我不明白在 SQL 查询中使用这种格式是多么容易。
回答by Peter L
Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.
到目前为止的答案帮助我想出了我的答案。我对 UTC 与本地时间持谨慎态度;刻度应始终为 UTC IMO。
public class Time
{
public static void Timestamps()
{
OutputTimestamp();
Thread.Sleep(1000);
OutputTimestamp();
}
private static void OutputTimestamp()
{
var timestamp = DateTime.UtcNow.Ticks;
var localTicks = DateTime.Now.Ticks;
var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
Console.Out.WriteLine("Timestamp = {0}. Local ticks = {1}. Local time = {2}.", timestamp, localTicks, localTime);
}
}
Output:
输出:
Timestamp = 636988286338754530. Local ticks = 636988034338754530. Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736. Local ticks = 636988034348878736. Local time = 2019-07-15 4:03:54 PM.