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

More than 1 year has passed since last update.

yyyymmddhhmmssfff+3桁ランダム数字

Last updated at Posted at 2023-12-03

業務で一意な一時ファイルを作成するために、
「yymmddhhmmssfff+3桁のランダム数字」を生成するコードをjavascriptで作成したのでここに残す。

※タイムスタンプのケツ3桁(fff): ミリ秒

※厳密には完全に同時刻に実行され、生成された3桁のランダム数字も一致する可能性が0ではないので、一意とは言えない。

// クラスのインスタンス化
const currentDate = new Date();
// 年
const year = currentDate.getFullYear();
// 月
const month = currentDate.getMonth() + 1;
// 日
const day = currentDate.getDate();
// 曜日のリスト
const dayOfWeek = ["日", "月", "火", "水", "木", "金", "土"];
// 曜日の番号を取得
const weekNumber = currentDate.getDay();
// 時間
const hour = currentDate.getHours();
// 分
const min = currentDate.getMinutes();
// 秒
const sec = currentDate.getSeconds();
// ミリ秒
const msec = currentDate.getMilliseconds();

//yyyyMMddHHmmssfff文字列を返却
const yyyyMMddHHmmssfff = () => {
  const date =
    year +
    String(month).padStart(2, "0") +
    String(day).padStart(2, "0") +
    String(hour).padStart(2, "0") +
    String(min).padStart(2, "0") +
    String(sec).padStart(2, "0") +
    String(msec).padStart(3, "0");
  console.log(date);
  return date;
};

//000~999変数を返却
const threeDigitRandom = () => {
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    console.log(random);
    return random
}
const timeStamp = yyyyMMddHHmmssfff();
const random = threeDigitRandom();

//yyyyMMddHHmmssfff+3桁ランダム値
const timeStampAndRandom = timeStamp+random;
console.log("yyyymmddhhmmssfff+★★★: " + timeStampAndRandom);
0
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
0
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?