Help us understand the problem. What is going on with this article?

日時を手軽に特定形式の文字列に変換する方法のメモ

More than 1 year has passed since last update.

日時を手軽に特定形式の文字列に変換する方法のメモ

sample.js
/**
 * 日時を特定形式の文字列に変換します。
 *
 * <p>date.toLocaleString() で取得される文字列について、
 * 日時の構成要素が年,月,日,時,分,秒となっていること。
 * また、日時の構成要素が数字のみで表現されていること。
 * 
 * @param date 変換対象のDateオブジェクト
 * @param delim1 日付の区切り文字。省略時は""(空文字)
 * @param delim2 日付と時刻の区切り文字。省略時は""(空文字)
 * @param delim3 時刻の区切り文字。省略時は""(空文字)
 * @return 変換した文字列
 */
function datetimeFormat(date, delim1, delim2, delim3) {

    var d1 = delim1 || "";
    var d2 = delim2 || "";
    var d3 = delim3 || "";

    var rgx1 = /\b(\d)\b/g;
    var rgx2 = /^\D*(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+).*$/;

    // ロケールに従った日付書式文字列を取得する
    // (書式例) 2017/1/1 0:00:00
    var s = date.toLocaleString();

    // 数字1桁のみのものはゼロ埋めして2桁にする
    s = s.replace(rgx1, "0$1");

    // 数字のみを抽出して好みの形式に置き換える
    // (注) 年,月,日,時,分,秒の順に並んでいること
    s = s.replace(rgx2, "$1" + d1+ "$2" + d1 + "$3" + d2 + "$4" + d3 + "$5" + d3 + "$6");

    return s;
}


// 以下、テストコード
var dt = new Date(2000, 0, 2, 3, 4, 5);

// まずは toLocaleString メソッドの実行結果をコンソールに出力
// [出力結果] 2000/1/2 3:04:05
console.log(dt.toLocaleString());

// [出力結果] 2000-01-02 03:04:05
console.log(datetimeFormat(dt, "-", " ", ":"))

// [出力結果] 2000/01/02_03.04.05
console.log(datetimeFormat(dt, "/", "_", "."))

// yyyyMMddHHmmss 形式に変換する
// 最後の3つの引数に空文字を指定
// [出力結果] 20000102030405
console.log(datetimeFormat(dt, "", "", ""))

// yyyyMMddHHmmss 形式に変換する
// 最後の3つの引数を省略
// [出力結果] 20000102030405
console.log(datetimeFormat(dt))





Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away