2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nodejsで 日付文字列とTimeStamp値を変換するスクリプト

Posted at

timeStamp値が必要となったため作った2本を記録しておく
コンソールからnodeで動くように作った

  • toTimestamp.js
  • fromTimestamp.js

使い方

・日本時間の日付から timestamp値を表示する

$ node toTimestamp.js "2025/1/1 12:0:0"
1735700400000

・timestamp値から 日本時間の日付を表示する

$ node fromTimestamp.js 1735700400000
2025/01/01 12:00:00

コード

toTimestamp.js
function toTimeStampFromJPstr(datetimestr) {
    // 日付文字列を分解
    const [year, month, day, hours, minutes, seconds] = datetimestr.split(/[-\/:\s]/).map(Number);
    // 東京(日本標準時)のタイムゾーンオフセット(JSTはUTC+9)
    const tokyoUtcOffset = 9 * 60 * 60 * 1000;
    // UTC時間に変換
    const utcDate = new Date(Date.UTC(year, month - 1, day, hours ?? 0, minutes ?? 0, seconds ?? 0));
    // JSTに調整
    utcDate.setTime(utcDate.getTime() - tokyoUtcOffset);
    return utcDate.getTime(); //unixtimeが欲しいならこれを1000で割ればいい
}

// 引数を取得
const args = process.argv.slice(2); // 最初の2つの要素(nodeとファイル名)は削除
if(args.length === 0) {
  console.error('引数が見つかりませんでした。');
}
// 例:引数の先頭を指定して適切に使用
const myArg = args[0];
const tokyoDate = toTimeStampFromJPstr(myArg);
console.log(tokyoDate);
fromTimestampToJPstr.js
function fromTimestampToJPstr(timestamp) {
  const date = new Date(timestamp); //(unixTime * 1000); // ミリ秒に変換

  // UTCの日付から日本標準時(JST)に調整
  const jstOffset = 9 * 60 * 60 * 1000; // JSTはUTC+9
  const jstDate = new Date(date.getTime() + jstOffset);

  // 年、月、日、時、分、秒を取得
  const year = jstDate.getUTCFullYear();
  const month = jstDate.getUTCMonth() + 1; // 0から始まるため +1
  const day = jstDate.getUTCDate();
  const hours = jstDate.getUTCHours();
  const minutes = jstDate.getUTCMinutes();
  const seconds = jstDate.getUTCSeconds();

  // フォーマットされた日付文字列を作成
  return `${year}/${zz(month)}/${zz(day)} ${zz(hours)}:${zz(minutes)}:${zz(seconds)}`;
}
// 2桁0埋め
const zz = zerozero
function zerozero(n){
  return `0${n}`.slice(-2)
}

// 引数を取得
const args = process.argv.slice(2); // 最初の2つの要素(nodeとファイル名)は削除
if (args.length === 0) {
  console.log('引数が見つかりませんでした。');
} 
// 例:引数の先頭を指定して適切に使用
const myArg = args[0];
const tokyoDate = fromTimestampToJPstr(myArg * 1);
console.log(tokyoDate);
2
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?