javascript 西暦から世紀を求める
- 作成日 2024.05.16
- javascript
- javascript

javascriptで、西暦から世紀を求めるサンプルコードを記述してます。
環境
- OS windows11 home
- ブラウザ chrome 124.0.6367.201
西暦から世紀
西暦から世紀に変換するには、100で割って切り上げすることで可能です。
<script>
function getCentury(year) {
// 切り上げ
let century = Math.ceil(year / 100);
return century;
}
console.log(getCentury(2101)); // 22世紀
console.log(getCentury(2100)); // 21世紀
console.log(getCentury(2024)); // 21世紀
console.log(getCentury(2021)); // 21世紀
console.log(getCentury(1999)); // 20世紀
console.log(getCentury(1900)); // 19世紀
</script>
その年を100で割って少数を切り捨てして「+1」しても可能で、その場合は、100で割れた場合は「-1」します。
<script>
function getCentury(year) {
// 世紀の切り捨て
let century = Math.floor(year / 100);
// 世紀の決定
if (year % 100 === 0) {
// 100の倍数の場合は、その前の世紀
century -= 1;
}
return century + 1;
}
console.log(getCentury(2101)); // 22世紀
console.log(getCentury(2100)); // 21世紀
console.log(getCentury(2024)); // 21世紀
console.log(getCentury(2021)); // 21世紀
console.log(getCentury(1999)); // 20世紀
console.log(getCentury(1900)); // 19世紀
</script>
サンプルコード
以下は、実行ボタンをクリックするとフォームに入力された値を、世紀に変換して表示するだけのサンプルコードとなります。
※cssには「Material Design for Bootstrap」を使用してます。関数はアロー関数を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
<!-- MDB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/7.2.0/mdb.min.css" rel="stylesheet" />
</head>
<body>
<div class="container text-center w-25" style="margin-top:150px">
<div id="result" class="alert alert-success"></div>
<div class="form-outline" data-mdb-input-init>
<input type="text" id="txt" class="form-control" />
</div>
<button id="bt" class="btn btn-success btn-rounded ">実行</button>
</div>
<script>
bt.addEventListener('click', () => {
// 表示
result.innerHTML = `${ getCentury(Number(txt.value))}世紀`;
});
const getCentury = (year) => {
// 世紀の切り捨て
let century = Math.floor(year / 100);
// 世紀の決定
if (year % 100 === 0) {
// 100の倍数の場合は、その前の世紀
century -= 1;
}
return century + 1;
}
</script>
</body>
</html>
表示されていることが確認できます。

-
前の記事
google workspace gmailの転送設定を行う 2024.05.16
-
次の記事
kotlin 割り算の余りを求める 2024.05.16
コメントを書く