C#時間轉整型(時間戳),模仿php strtotime函數的部分功能


今天需要將一個基於MS SQL數據庫的新聞系統數據導入phpcms v9,源系統新聞日期格式為"2014-01-15 10:45:49",
而phpcms中使用的是整型時間戳,在php中很簡單,用strtotime()即可;
在C#中,需要自己寫函數,步驟如下:

步驟1.先計算phpcms中時間戳所用基准時間:
1             TimeSpan ts = new TimeSpan(0,0,0,1389753949);
2             DateTime now = Convert.ToDateTime("2014-01-15 10:45:49");
3             DateTime baseTime = now - ts;
4             Response.Write(baseTime.ToString());
5             Response.Write("<br/>");

  顯示在頁面上的是1970-1-1 8:00:00,得到了基准時間

步驟2.轉換時間為整型時間戳:
1  //基准為"1970-1-1 8:00:00"時間轉整數
2             baseTime = Convert.ToDateTime("1970-1-1 8:00:00");
3             ts = DateTime.Now - baseTime;
4             long intervel = (long)ts.TotalSeconds;
5             Response.Write("當前時間轉換為:" + intervel.ToString());
得出的整數是從1970-1-1 8:00:00到當前的秒數,即phpcms v9 中 v9_news 表里 inputtime列、updatetime列值來源

 

 
        

附錄:

日期轉換為時間戳

PHP 提供了函數可以方便的將各種形式的日期轉換為時間戳,該類函數主要是:

  • strtotime():將任何英文文本的日期時間描述解析為時間戳。
  • mktime():從日期取得時間戳。

strtotime()

strtotime() 函數用於將英文文本字符串表示的日期轉換為時間戳,為 date() 的反函數,成功返回時間戳,否則返回 FALSE 。

語法:

int strtotime ( string time [, int now] )

參數 time 為被解析的字符串,是根據 GNU 日期輸入格式表示的日期。

例子:

<?php
echo strtotime("2009-10-21 16:00:10");	//輸出 1256112010
echo strtotime("10 September 2008");	//輸出 1220976000
echo strtotime("+1 day"), "<br />";	//輸出明天此時的時間戳
?>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM