moment.js を使った日付処理の基本
VueやReactのプロジェクトでは、日付操作ライブラリとして moment.js を導入することが一般的です。以下はその基本的な設定と使用方法です。
中国語ロケールの設定
アプリ全体で中国語表示を行う場合、エントリーファイル(例: main.js または app.vue)でロケールを設定します。
import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');
日付のフォーマット出力
現在時刻をさまざまな形式で表示する例:
import moment from 'moment';
// 使用例
const now = moment();
console.log(now.format('YYYY-MM-DD HH:mm:ss')); // 2021-12-06 11:15:30
console.log(now.format('LLLL')); // 2021年12月6日星期一上午11点15分
日付とタイムスタンプの相互変換
特定の日時をミリ秒に変換
文字列形式の日付をUnixタイムスタンプ(ミリ秒)に変換できます。
const timeStr = "2020-07-20 10:23:21";
const timestamp = new Date(timeStr).getTime(); // 1595211801000
現在時刻をミリ秒で取得
const currentTimestamp = Date.now(); // 例: 1638760198019
秒数から「~時間~分~秒」形式へ変換
経過時間を人間が読みやすい形式に整形する関数。
function formatDuration(seconds) {
const duration = moment.duration(seconds, 'seconds');
const days = Math.floor(duration.asDays());
const hours = duration.hours();
const minutes = duration.minutes();
const secs = duration.seconds();
let result = '';
if (days > 0) result += `${days}日`;
if (hours > 0) result += `${hours}時間`;
if (minutes > 0) result += `${minutes}分`;
result += `${secs}秒`;
return result;
}
// 使用例
console.log(formatDuration(7265)); // 2時間1分5秒
文字列を日付形式に整形する方法
正規表現を使ったフォーマット変換(パターン1)
const dateStr = '20130505';
const formatted = dateStr.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1-$2-$3');
// 結果: "2013-05-05"
replaceAll と関数置換によるカスタム区切り(パターン2)
const input = '20190912';
const regex = /(\d{4})(\d{2})(\d{2})/g;
function replaceWithHyphens(match, year, month, day) {
return [year, month, day].join(' - ');
}
const result = input.replaceAll(regex, replaceWithHyphens);
// 結果: "2019 - 09 - 12"
ローカル時間とUTC時間の扱い
ローカル時刻の取得
new Date().toLocaleString();
// 例: "2020/1/8 下午6:36:08"
ISO形式(UTC)での出力
国際標準形式で日時を出力。日本時間との時差を考慮する場合は補正が必要です。
// 北京時間(UTC+8)に合わせて調整
const utcTime = new Date(Date.now() + 8 * 3600 * 1000).toISOString();
// 例: "2020-01-08T10:36:02.157Z"
独自のフォーマット関数実装
プロトタイプ拡張によるformatメソッド追加
Date.prototype.format = function(fmt) {
const o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'h+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
'q+': Math.floor((this.getMonth() + 3) / 3),
'S': this.getMilliseconds()
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(this.getFullYear() + '').substr(4 - RegExp.$1.length)
);
}
for (let k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
const val = o[k] + '';
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? val : ('00' + val).slice(-RegExp.$1.length)
);
}
}
return fmt;
};
// 使用例
console.log(new Date().format('yyyy-MM-dd hh:mm:ss'));
簡易な現在時刻フォーマット関数
function getNowFormatDate() {
const date = new Date();
let month = date.getMonth() + 1;
let strDate = date.getDate();
if (month < 10) month = '0' + month;
if (strDate < 10) strDate = '0' + strDate;
return date.getFullYear() + '-' + month + '-' + strDate +
' ' + date.getHours() + ':' + date.getMinutes() +
':' + date.getSeconds();
}
console.log(getNowFormatDate());
ISO文字列から日時を抽出する方法
function getCurrentDateTimeString() {
const iso = new Date(Date.now() + 8 * 3600 * 1000).toISOString();
const [datePart, timePart] = iso.split('T');
const time = timePart.split('.')[0];
return `${datePart} ${time}`;
}
console.log(getCurrentDateTimeString());