[C#]DateTimeから秒のみを取得するには?

C#

どうも、ちょげ(@chogetarou)です。

DateTimeから秒のみを取得する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

DateTimeから秒のみを取得する方法は、2つあります。

Second

1つは、Secondプロパティを使う方法です。

具体的な方法としては、「date.Second」のように、DateTimeのSecondプロパティにアクセスします。

int second = date.Second;

DateTimeのSecondプロパティにアクセスすることで、DateTimeの秒のみを数値として取得できます。

使用例

using System;

public class Sample 
{
    public static void Main() 
    {
        DateTime currentDay = DateTime.Now;
        
        int second = currentDay.Second;
        
        System.Console.WriteLine(currentDay);
        System.Console.WriteLine(second);
    }
}
出力:
8/31/2022 12:40:07 AM
7

ToString()

もう1つは、ToString()を使う方法です。

まず、「date.Second」のように、DateTimeのSecondプロパティにアクセスします。

そして、SecondプロパティからToString()を呼び出します。

string second = date.Second.ToString();

上記のToString()は、DateTimeの秒のみを文字列として取得します。

使用例

using System;

public class Sample 
{
    public static void Main() 
    {
        DateTime currentDay = DateTime.Now;
        
        string second = currentDay.Second.ToString();
        
        System.Console.WriteLine(currentDay);
        System.Console.WriteLine(second);
    }
}
出力:
8/31/2022 12:42:43 AM
43
スポンサーリンク

まとめ

DateTimeから秒のみを取得する方法は、次の2つです。

  • Secondプロパティを使う方法
    int second = date.Second;
  • ToString()を使う方法
    string second = date.Second.ToString();

コメント

タイトルとURLをコピーしました