[C#] 時間比對,時間差-MSSQL的sysdatetime compare

在程式設計中,無可避免的你一定會遇到時間比對的問題,比如像下面的例子

我要用資料庫記錄某一個使用者的離開時間,若離開時間超過半小時就執行某個程式

這時你就要用到時間差的做法了

以下是簡單的範例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Diagnostics;

namespace samplecode
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get Data from MSSQL
            string connectionString = “Data Source=127.0.0.1;Initial Catalog=mydb;Persist Security Info=True;User ID=sqladmin;Password=abc@1234”;
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();

                using (SqlCommand command = new SqlCommand(“SELECT *,datenow=SYSDATETIME() FROM publish”, con)) //除了將table所有欄位取出,也一併取出資料庫現在時間
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {

                           //reader.GetDateTime(7)是datenow=SYSDATETIME(),reader.GetDateTime(6)是使用者離開時間
                           double ts = new TimeSpan(reader.GetDateTime(7).Ticks – reader.GetDateTime(6).Ticks).TotalMinutes;
                            if (ts > 30)
                            {
                                Console.WriteLine(“live “+ reader.GetString(0)+ ” stop more than 30 minutes”);
                            }
                     }

                }
            }
        }
    }
}

上面這個例子是以分鐘為單位,所以使用TotalMinutes,當然真實使用上你會遇到其他的比較單位.

比如說以秒,小時,天來做為比較單位,這時你就要視需求來改變.

豪秒 TotalMilliseconds

秒 TotalSeconds

分 TotalMinutes

時 TotalHours

天 TotalDays

 

Category: 來玩C#