Java與C#實現時間轉換

來源:互聯網
上載者:User

這兩天做了一個Web Service,要記錄操作時間,定義為long型資料,因為 Java中可以把目前時間表示成long類型。

Java中可以用 System.currentTimeMillis() 擷取目前時間的long形式,它 的標示形式是從1970年1月1日起的到當前的毫秒的數。Web Service 是用Java寫 的,把這個long型資料轉成timestamp再存入MySQL,所以用調用我們的Web Service可以直接把這個值傳入。

但是.Net下計算時間的方式不太一樣,它是計算單位是Ticks,關於Ticks,msdn上是這樣說的:

A single tick represents one hundred nanoseconds or one ten- millionth of a second. The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001.

就是從公元元年元月1日午夜到指定時間的千萬分之一秒了,為了和Java比較 ,說成萬分之一毫秒。

( System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks)/10000;

如果要得到Java中 System.currentTimeMillis() 一樣的結果,就可以寫成 上面那樣,也可以這樣寫:

TimeSpan ts=new TimeSpan( System.DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1, 0, 0, 0).Ticks);

(long)ts.TotalMilliseconds;

需要注意的是這裡是用的 System.DateTime.UtcNow 而不是 System.DateTime.Now ,因為我們在東八區,如果用後面那種形式就會發現時間 會和想象當中的差了8個小時。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.