[Tool] 日時をUnixtimeへ変換する
See the Pen Untitled by Mitsuaki KIDA (@kidatti) on CodePen.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Convert Datetime</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script>
function convert() {
const dateString = document.getElementById("date").value;
const timeString = document.getElementById("time").value;
if (!dateString) {
alert("日付を入力してください");
return;
}
if (!timeString) {
alert("時間を入力してください");
return;
}
// タイムゾーン
const timezoneOffset = new Date().getTimezoneOffset();
const timezoneSign = timezoneOffset <= 0 ? "+" : "-";
const timezoneOffsetHourZeroPadding = String(Math.abs(timezoneOffset / 60)).padStart(2, "0")
const timezone = timezoneSign + timezoneOffsetHourZeroPadding
// ISO8601
const datetimeString = dateString + "T" + timeString + ":00" + timezone + ":00"
document.getElementById("iso8601").value = datetimeString;
// Unixtime
const datetime = new Date(datetimeString);
const unixtime = Math.floor(datetime.getTime() / 1000)
document.getElementById("unixtime").value = unixtime;
}
</script>
</head>
<body>
<div class="container">
<form class="row">
<div class="col-auto">
<input type="date" class="form-control" id="date" required>
</div>
<div class="col-auto">
<input type="time" class="form-control" id="time" required>
</div>
<div class="col-auto">
<button type="button" class="form-control" onclick="convert()">変換</button>
</div>
<div class="col-auto">
<input type="text" class="form-control" id="iso8601">
</div>
<div class="col-auto">
<input type="text" class="form-control" id="unixtime">
</div>
</form>
</div>
</body>
</html>