代码之家  ›  专栏  ›  技术社区  ›  RGriffiths

javascript设置日期格式,包括带日期和月份的0

  •  0
  • RGriffiths  · 技术社区  · 6 年前

    实际上,我试图将2019-02-09等日期转换为2019-02-2019。我有以下资料:

    var newDate = new Date('2019-02-09');
    strDate = newDate.getDate() + "-" + (newDate.getMonth() + 1) + "-" + newDate.getFullYear();
    

    有效,但将于2019年2月9日产出。是否有一个简洁的方法(即不检查getDate和getMonth小于10)来获得2019年2月9日的输出?

    3 回复  |  直到 6 年前
        1
  •  0
  •   Damien    6 年前

    你可以用 padStart 为了实现你的目标。

    var newDate = new Date('2019-02-09');
    strDate = newDate.getDate().toString().padStart(2, "0") + "-" + (newDate.getMonth() + 1).toString().padStart(2, "0") + "-" + newDate.getFullYear();
    
    console.log(strDate);
        2
  •  3
  •   gaetanoM    6 年前

    使用 toLocaleDateString() :

    var dt = new Date('2019-02-09');
    
    var x = dt.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' })
              .replace(/[^0-9]/g, '-');
    
    
    
    console.log(x);
        3
  •  1
  •   AndrewL64    6 年前

    只使用 toLocaleDateString() 方法与选择 en-GB 作为返回日期的区域设置 DD/MM/YYYY 格式化并使用 split() join() 或要替换的regex / 具有 - 这样地:


    拆分连接方法:

    var newDate = new Date('2019-02-09');    
    strDate = newDate.toLocaleDateString('en-GB').split("/").join("-");    
    alert(strDate);

    Regex:

    var newDate = new Date('2019-02-09');    
    strDate = newDate.toLocaleDateString('en-GB').replace(/[^0-9]/g, '-');    
    alert(strDate);