0
0

生年月日から年齢を計算する方法を各プログラミング言語で書いてみた

Last updated at Posted at 2024-08-21

はじめに

プログラミングでよくあるタスクの一つに、生年月日から年齢を計算することがあります。今回は、各プログラミング言語でこのタスクを1行で実装してみました。どの言語でも、標準ライブラリを活用すれば簡単に計算できます。

Python

age = (datetime.datetime.now() - datetime.datetime(1984, 8, 21)).days // 365

Pythonでは、datetimeモジュールを使い、現在の日付と生年月日との差を日数で計算し、年数に換算しています。

JavaScript

const age = Math.floor((new Date() - new Date('1984-08-21')) / (365.25 * 24 * 60 * 60 * 1000));

JavaScriptでは、Dateオブジェクトを利用して、生年月日と現在の日付の差をミリ秒で計算し、年数に換算しています。

===
ミリ秒意識しない記載方法は以下(推奨)

const age = ~~((new Date().toLocaleString('ja', {dateStyle: 'short'}).replace(/\D/g, '') - 19840821) / 1e4);

Ruby

age = ((Time.now - Time.new(1984, 8, 21)) / (60 * 60 * 24 * 365)).to_i

Rubyでは、Timeオブジェクトを使用し、現在の時間と生年月日との差を秒で計算し、年数に換算しています。

PHP

$age = floor((time() - strtotime('1984-08-21')) / (365.25 * 24 * 60 * 60));

PHPでは、strtotime関数を使って生年月日をタイムスタンプに変換し、現在のタイムスタンプとの差から年数を計算しています。

Go

age := int(time.Since(time.Date(1984, 8, 21, 0, 0, 0, 0, time.UTC)).Hours() / 24 / 365)

Goでは、timeパッケージを使い、生年月日と現在の日付との差を時間単位で取得し、それを年数に換算しています。

Java

int age = Period.between(LocalDate.of(1984, 8, 21), LocalDate.now()).getYears();

Javaでは、Periodクラスを使い、生年月日から現在の年齢を計算します。

C#

int age = DateTime.Now.Year - new DateTime(1984, 8, 21).Year - (DateTime.Now.DayOfYear < new DateTime(1984, 8, 21).DayOfYear ? 1 : 0);

C#では、現在の年と生年月日の年の差から年齢を計算し、誕生日が過ぎていない場合には1歳減らします。

Swift

let age = Calendar.current.dateComponents([.year], from: DateComponents(year: 1984, month: 8, day: 21).date!, to: Date()).year!

Swiftでは、CalendarDateComponentsを使って年齢を計算します。

Kotlin

val age = Period.between(LocalDate.of(1984, 8, 21), LocalDate.now()).years

Kotlinでは、Periodクラスを使用して、生年月日から年齢を計算します。

Rust

let age = Utc::now().signed_duration_since(Utc.ymd(1984, 8, 21).and_hms(0, 0, 0)).num_days() / 365;

Rustでは、chronoクレートのUtcを使い、日数を計算して年齢を算出します。

TypeScript

const age = Math.floor((new Date().getTime() - new Date('1984-08-21').getTime()) / (365.25 * 24 * 60 * 60 * 1000));

TypeScriptでも、JavaScriptと同様にDateオブジェクトを利用して計算します。

終わりに

上記の例は、生年月日から年齢を計算する方法を簡潔に示しています。実際には、誕生日がまだ来ていない場合や閏年などを考慮する必要があるかもしれません。それでも、各言語でこれをどのように実装するかを理解するための良い練習になります。

0
0
4

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
0
0