目次
Date と基本操作
Date オブジェクトの基本
const now = new Date();
console.log(now); // 現在時刻(ローカルタイム)に対応する Date オブジェクトDate は内部的には「1970-01-01T00:00:00Z からのミリ秒数」を持っているオブジェクトです。
const timestamp = Date.now(); // ミリ秒の数値(number)
console.log(timestamp);
const d = new Date(timestamp); // 数値から Date 生成Date.now()は「現在時刻のミリ秒タイムスタンプ」だけが欲しいときに便利new Date(ms)は、そのミリ秒値からDateを復元
いろいろなコンストラクタ
// 1. 現在時刻
new Date();
// 2. ミリ秒指定
new Date(0); // 1970-01-01T00:00:00.000Z
// 3. 年/月/日 など個別指定(ローカルタイム基準)
new Date(2025, 0, 1); // 2025年1月1日 00:00:00 ローカル
new Date(2025, 0, 1, 9, 30); // 2025-01-01 09:30
// 4. 文字列から(ISO 形式推奨)
new Date("2025-01-01T00:00:00Z"); // UTC
new Date("2025-01-01"); // 環境依存の解釈もありうるので推奨度低めポイント:
- 文字列からのパースは ISO 8601 形式(
YYYY-MM-DDTHH:mm:ss.sssZ)がおすすめ - ロケール依存の
"1/2/2025"などは極力避ける(ブラウザごとに解釈が変わりうる)
日付・時刻の取得(ゲッター)
const d = new Date(2025, 0, 2, 15, 45); // 2025-01-02 15:45
console.log(d.getFullYear()); // 2025
console.log(d.getMonth()); // 0 (0=1月, 11=12月)
console.log(d.getDate()); // 2 (日)
console.log(d.getDay()); // 4 (0=日曜〜6=土曜)
console.log(d.getHours()); // 15
console.log(d.getMinutes()); // 45
console.log(d.getSeconds()); // 0
console.log(d.getMilliseconds()); // 0getMonth()は 0 始まり(ここだけ特にハマりやすい)
UTC 版のゲッターもあります:
d.getUTCFullYear();
d.getUTCMonth();
d.getUTCDate();
...ローカルタイムと UTC の違いを明確にしたい場合に使います。
日付・時刻の更新(セッター)
const d = new Date(2025, 0, 1); // 2025-01-01
d.setFullYear(2030);
d.setMonth(5); // 6月(0=1月)
d.setDate(15); // 15日
console.log(d); // 2030-06-15 ...日付加算は「ミリ秒を足す」か「setXXX 系を使う」かの2パターン。
ミリ秒を足す(シンプルで安全)
const dayMs = 24 * 60 * 60 * 1000;
const d1 = new Date();
const d2 = new Date(d1.getTime() + dayMs * 7); // 7日後setDate を使う
const d = new Date(2025, 0, 25); // 1月25日
d.setDate(d.getDate() + 10); // 10日後
console.log(d); // 2月4日(自動で月繰り上がり)setDate/setMonthなどは、範囲を超えると自動で繰り上がり・繰り下がりする
日付差の計算
const start = new Date(2025, 0, 1);
const end = new Date(2025, 0, 10);
const diffMs = end - start; // 数値として引き算できる
const diffDays = diffMs / (1000 * 60 * 60 * 24);
console.log(diffDays); // 9Date同士は数値引き算ができ、ミリ秒差 が返る- 日数・時間数にしたければ 1000, 60, 60, 24 で割る
JSON とシリアライズ/デシリアライズ
JSON は「データを文字列にして保存・通信するときのフォーマット」です。
JSON.stringify:JS値 → JSON文字列
const obj = {
name: "Taro",
age: 20,
admin: false,
skills: ["js", "html"],
};
const json = JSON.stringify(obj);
console.log(json);
// {"name":"Taro","age":20,"admin":false,"skills":["js","html"]}フォーマット:
- 文字列は 必ずダブルクォート
"..." - オブジェクトのキーも
"key"のようにダブルクォート undefined/function/symbolなどは原則として無視 ornullになる
const obj = { a: 1, b: undefined, c: () => {} };
console.log(JSON.stringify(obj)); // {"a":1}整形(インデント)付きで出力
const pretty = JSON.stringify(obj, null, 2);
console.log(pretty);
/*
{
"name": "Taro",
"age": 20,
"admin": false,
"skills": [
"js",
"html"
]
}
*/JSON.parse:JSON文字列 → JS値
const json = '{"name":"Taro","age":20}';
const obj = JSON.parse(json);
console.log(obj.name); // "Taro"- JSON が不正な形式だと 例外(SyntaxError)が投げられる ので、
外部入力(APIレスポンスなど)には try/catch を組み合わせることが多いです。
日付文字列を Date に戻す例
const data = {
name: "Taro",
createdAt: new Date(),
};
const json = JSON.stringify(data);
console.log(json);
// {"name":"Taro","createdAt":"2025-11-20T08:00:00.000Z"} みたいな文字列
const revived = JSON.parse(json, (key, value) => {
if (key === "createdAt") {
return new Date(value);
}
return value;
});
console.log(revived.createdAt instanceof Date); // trueJSON で表現できないもの
JSON が扱える型はだいたい次の通りです:
- オブジェクト
{ ... } - 配列
[ ... ] - 文字列
- 数値(
number)※NaN/Infinityはnullになる - 真偽値
true/false null
扱えないもの:
undefined- 関数
SymbolBigInt- 循環参照を含むオブジェクト
const obj = {};
obj.self = obj;
// JSON.stringify(obj); // TypeError: Converting circular structure to JSONRegExp と簡単な正規表現
正規表現は 「文字列パターンのミニ言語」 です。
最初は「検索・マッチング」に限定して使えるだけで十分です。
正規表現リテラルと RegExp コンストラクタ
const re1 = /abc/; // リテラル
const re2 = new RegExp("abc"); // コンストラクタ(動的生成にも使える)- 基本的にはリテラル
/.../で書くことが多い - フラグ(オプション)は
/abc/g,/abc/iのように末尾に付ける
代表的なフラグ:
g:global(複数マッチ)i:ignore case(大文字小文字無視)m:multiline(複数行)u:Unicode サポート(👍などのコードポイントを正しく扱う)
test:マッチするかどうか
const re = /hello/;
console.log(re.test("hello world")); // true
console.log(re.test("hi")); // falsetrue / falseが欲しいときはtestがシンプル
文字クラス・量指定子の基本
いきなり全部覚えなくてよいですが、最低限よく使うもの:
.:任意の1文字\d:数字(0〜9)\w:英数字+アンダースコア\s:空白[abc]:a または b または c[^abc]:a, b, c 以外
量指定子:
a*:a が0回以上a+:a が1回以上a?:a が0回か1回a{3}:a がちょうど3回a{1,3}:a が1〜3回
例:数字だけかどうかチェック
const re = /^\d+$/;
console.log(re.test("123")); // true
console.log(re.test("12a3")); // false^:文字列の先頭$:文字列の末尾
→ 全体が数字だけかどうか、を表現
文字列メソッドとの組み合わせ
RegExp は String のメソッドとも連携します。
const s = "hello 123 world 456";
// match(全マッチを配列で)
console.log(s.match(/\d+/g)); // ["123", "456"]
// replace(置換)
console.log(s.replace(/\d+/g, "#")); // "hello # world #"Intl 概観(国際化のための標準 API)
Intl は「国際化(i18n)サポートのための組み込みオブジェクト」です。
ここでは主に 3つ:
Intl.NumberFormatIntl.DateTimeFormatIntl.Collator
をざっくり押さえます。
ロケール(ja-JP, en-US など)の考え方
const locale = navigator.language; // ブラウザならユーザーのロケール
console.log(locale); // 例: "ja-JP"ja-JP:日本語(日本)en-US:英語(アメリカ)fr-FR:フランス語(フランス)
Intl の各クラスは new Intl.Xxx(locale, options) のように使うのが基本です。
Intl.NumberFormat:数値フォーマット
基本
const nf = new Intl.NumberFormat("ja-JP");
console.log(nf.format(1234567.89)); // "1,234,567.89" みたいな形式通貨表現:
const yen = new Intl.NumberFormat("ja-JP", {
style: "currency",
currency: "JPY",
});
console.log(yen.format(123456)); // "¥123,456"style: "currency":通貨表現currency: "JPY":通貨コード(USD, EUR など)
パーセント:
const percent = new Intl.NumberFormat("en-US", {
style: "percent",
maximumFractionDigits: 1,
});
console.log(percent.format(0.1234)); // "12.3%" のような文字列Intl.DateTimeFormat:日付・時刻フォーマット
const d = new Date(2025, 0, 2, 15, 45);
const f1 = new Intl.DateTimeFormat("ja-JP");
console.log(f1.format(d)); // "2025/1/2" などオプションでかなり細かく制御できます:
const f2 = new Intl.DateTimeFormat("ja-JP", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
console.log(f2.format(d)); // "2025/01/02 15:45" のような文字列year: “numeric” / “2-digit”month: “numeric” / “2-digit” / “long” / “short”day: “numeric” / “2-digit”hour,minute,secondなども指定可
ロケールを変えるだけでフォーマットも変わる:
const us = new Intl.DateTimeFormat("en-US", {
dateStyle: "medium",
timeStyle: "short",
});
console.log(us.format(d)); // "Jan 2, 2025, 3:45 PM" などIntl.Collator:文字列の比較(ソート)
const items = ["ä", "z", "a"];
items.sort(); // 単純なバイト比較(ロケール無視)
const collator = new Intl.Collator("de-DE"); // ドイツ語
items.sort(collator.compare);
console.log(items);- ロケールに応じた 文字列の並び順 を提供してくれる
- 日本語の五十音順や、アクセント付き文字の扱いなど、
細かいルールを自前で実装せずに任せられる
コメント