且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中显示当前日期时间的微秒?

更新时间:2022-11-08 23:14:04

当我尝试时:

When I try it:
DateTime serverDate = DateTime.Now;
string currentDateString = string.Format("{0}", serverDate.ToString("yyyyMMddHHmmssffffff"));
Console.WriteLine(currentDateString);

我得到了我的期望:

I get what I expect:

20170527091049145901
yyyyMMddHHmmssffffff



所以我猜你正在提取的serverDate值(从哪里来,我不知道)没有一个低于第二个的组件。

使用调试器来查看确切的它包含什么,如果Millisecond属性为0,那么当你期望一个值时,它就会打印为000000。

然后你可以查看DateTime源来找出原因。 />




如何通过T-sql获得当前日期时间的微秒?





获得任何其他信息的方式相同:只需将其读入DateTime变量:


So I'd guess that the "serverDate" value you are fetching (from where, I don't know) does not have a component below the second.
Use the debugger to look at exactly what it contains, and if the Millisecond property is 0, then that's why it prints as "000000" when you expect a value.
You can then look at the DateTime source to find out why.


"how can i get Microseconds of current date time by T-sql ?"


Same way you get any other info: just read it into a DateTime variable:

try
    {
    using (SqlConnection con = new SqlConnection(strConnect))
        {
        con.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 InsertDate, GETDATE() FROM Videos", con))
            {
            DataTable dt = new DataTable();
            using (SqlDataReader reader = cmd.ExecuteReader())
                {
                while (reader.Read())
                    {
                    DateTime dt1, dt2;
                    dt1 = (DateTime)reader[0];
                    dt2 = (DateTime)reader[1];
                    string dt1s = string.Format("{0}", dt1.ToString("yyyyMMddHHmmssffffff"));
                    string dt2s = string.Format("{0}", dt2.ToString("yyyyMMddHHmmssffffff"));
                    Console.WriteLine("{0}:{1}", dt1s, dt2s);
                    }
                }
            }
        }
    }
catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    }

当我运行时,我得到:

When I run this, I get:

20120624125436677000:20170527113211523000
20120527083918187000:20170527113211523000
20120527084000500000:20170527113211523000
20160603074757507000:20170527113211523000
20141012123141300000:20170527113211523000

这表明SQL Server的刻度是毫秒

Which indicates that SQL Server ticks are to the millisecond