1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

プログラミング言語別のDate型操作方法

Posted at

記事を書こうと思ったきっかけ

今回この記事を書こうと思ったのは、仕事や自己学習の中で日付(Date型)を扱う機会があったことがきっかけです。仕事では主にVB.NETを使用し、自己学習ではReactを使って開発をしていますが、ふと「日付を扱う方法は、言語によってどのように異なるのだろう?」と疑問を持ちました。そこで調べた内容を整理し、この記事としてまとめました。
今回調べた言語は以下の4つです。

  • Java
  • Python
  • JavaScript
  • VB.NET

JavaでのDate型の扱い

Javaでは、日付操作に古くからjava.util.Dateが使用されてきました。近年ではjava.time.LocalDateやZonedDateTimeなどのモダンなAPIが推奨されています。日付のフォーマット変換にはSimpleDateFormatやDateTimeFormatterが使われ、タイムゾーンの考慮も簡単に行えます。これにより、異なる地域間での正確な時刻操作や、過去・未来の日付演算が容易になります。

// 必要なクラスをインポートします
import java.time.LocalDate; // 日付を表すためのクラス
import java.time.format.DateTimeFormatter; // 日付フォーマットを扱うためのクラス

public class DateExample {
    public static void main(String[] args) {
        // 現在の日付を取得
        LocalDate today = LocalDate.now(); 
        System.out.println("Today: " + today); // 例: 2024-10-11

        // 日付を指定のフォーマットに変換
        // DateTimeFormatterは、日付を"yyyy/MM/dd"形式にフォーマット
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String formattedDate = today.format(formatter);
        System.out.println("Formatted Date: " + formattedDate); // 例: 2024/10/11

        // 3日後の日付を計算
        LocalDate futureDate = today.plusDays(3);
        System.out.println("Future Date: " + futureDate); // 例: 2024-10-14
    }
}
  • インポート文: LocalDateは日付のみを扱い、DateTimeFormatterでフォーマット変換を行います。
  • 現在の日付取得: LocalDate.now()で現在の日付を取得し、標準フォーマットで表示。
  • フォーマット変換: DateTimeFormatter.ofPattern("yyyy/MM/dd")で日付を任意の形式に変換。
  • 日付演算: plusDays(3)で3日後の日付を取得し、結果を表示。

PythonでのDate型の扱い

Pythonではdatetimeモジュールが標準で提供されており、日付や時刻の操作が簡単に行えます。日付フォーマットの変換にはstrftimeやstrptimeを使用し、timedeltaで日付の加算・減算が可能です。また、pytzやzoneinfoモジュールでタイムゾーン対応も行えます。

# 必要なクラスをインポートします
from datetime import datetime, timedelta  # datetimeは日付と時刻を扱うモジュール, timedeltaは日付演算用

# 現在の日付を取得
today = datetime.now()
print("Today:", today.strftime("%Y-%m-%d"))  # 現在の日付を '年-月-日' 形式で表示

# 3日後の日付を計算
future_date = today + timedelta(days=3)
print("Future Date:", future_date.strftime("%Y-%m-%d"))  # 3日後の日付を表示

# 日付文字列を日付オブジェクトに変換
date_str = "2024-10-11"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d")  # 文字列から日付オブジェクトに変換
print("Parsed Date:", parsed_date.strftime("%Y-%m-%d"))  # 変換した日付を表示
  • インポート文: datetimeで日付と時刻を扱い、timedeltaで日付の演算を行います。
  • 現在の日付取得: datetime.now()で現在の日付と時刻を取得し、strftime()でフォーマット。
  • 日付演算: timedelta(days=3)で3日後の日付を計算。
  • 文字列からの変換: strptime()を使って、日付文字列をdatetimeオブジェクトに変換します。

JavaScriptでのDate型の扱い

JavaScriptの標準Dateオブジェクトは、シンプルながらも多くの日付操作をサポートしています。例えば、toISOStringやtoLocaleDateStringで日付フォーマットを簡単に変換可能です。複雑な操作にはmoment.jsやdate-fnsなどのライブラリがよく使われ、タイムゾーンの処理にはIntl.DateTimeFormatやTemporal APIが役立ちます。

// 現在の日付を取得
const today = new Date();  // Dateオブジェクトで現在の日付と時刻を取得
console.log("Today:", today.toISOString().split('T')[0]);  // ISO形式で表示し、時刻を除去

// 3日後の日付を計算
const futureDate = new Date();  // 新たにDateオブジェクトを作成
futureDate.setDate(today.getDate() + 3);  // getDate()で日付を取得し、3日加算
console.log("Future Date:", futureDate.toISOString().split('T')[0]);  // 計算結果を表示

// 日付文字列をDateオブジェクトに変換
const dateStr = "2024-10-11";
const parsedDate = new Date(dateStr);  // 日付文字列からDateオブジェクトを作成
console.log("Parsed Date:", parsedDate.toISOString().split('T')[0]);  // 変換結果を表示
  • 現在の日付取得: new Date()で現在の日付を取得し、toISOString()で標準フォーマットに変換。
  • 日付演算: setDate()を使用して、現在の日付に3日を加算しています。
  • 文字列からの変換: new Date()に日付文字列を渡し、Dateオブジェクトに変換します。

VB.NETでのDate型の扱い

VB.NETでは、DateTime構造体が日付と時刻の操作に使われます。VB.NETの構文はシンプルでわかりやすく、日付の加算・減算やフォーマットのカスタマイズが容易です。また、DateTimeには多くの便利なメソッドが用意されており、時間の計算や日付フォーマットの変換が簡単に行えます。タイムゾーンの処理には、DateTimeOffsetやTimeZoneInfoを使用することが推奨されています。

Module DateExample
    Sub Main()
        ' 現在の日付と時刻を取得
        Dim today As DateTime = DateTime.Now
        Console.WriteLine("Today: " & today.ToString("yyyy/MM/dd"))  ' 年/月/日形式で表示

        ' 3日後の日付を計算
        Dim futureDate As DateTime = today.AddDays(3)  ' 3日後の日付を計算
        Console.WriteLine("Future Date: " & futureDate.ToString("yyyy/MM/dd"))  ' 計算結果を表示

        ' 日付文字列をDateTimeオブジェクトに変換
        Dim dateStr As String = "2024-10-11"
        Dim parsedDate As DateTime = DateTime.Parse(dateStr)  ' 文字列からDateTimeオブジェクトに変換
        Console.WriteLine("Parsed Date: " & parsedDate.ToString("yyyy/MM/dd"))  ' 変換結果を表示
    End Sub
End Module
  • 現在の日付と時刻の取得: DateTime.Nowを使用して現在の日付と時刻を取得します。ToString("yyyy/MM/dd")で日付を年/月/日形式にフォーマットします。
  • 日付の演算: AddDays()メソッドを使用して、現在の日付に3日を加算しています。
    • 文字列からDateTimeオブジェクトへの変換: DateTime.Parse()メソッドを使って、日付の文字列(例: "2024-10-11")をDateTimeオブジェクトに変換します。

まとめ

どの言語でも標準機能としてDate型が用意されていますが、時代とともにより扱いやすいAPIやライブラリが登場していることがわかりました。基本的な使い方は似ていますが、最新の情報や新しい機能を常にキャッチアップしていくことが重要だと感じました。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?