js 最简单的四种获取本地时间格式

本文介绍了四种不同的JavaScript日期时间格式化方法,包括直接使用Date对象的方法、利用正则表达式替换、手动拼接字符串以及自定义函数实现。这些方法可以帮助开发者根据实际需求选择合适的日期时间显示格式。

第一种正则 年/月/日/时分秒

let date = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');

console.log(date);   // 2018-03-26 15:41:10

第二种正则 年/月/日/时分秒


let date = new Date();
let strDate = date.toLocaleString().replace(/[年月]/g, '-').replace(/[日上下午]/g, '');
console.log(strDate);  //  2018/3/26 3:42:25

第三种获取 年-月-日


let nowDate = new Date();
let year = nowDate.getFullYear();
let month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
          : nowDate.getMonth() + 1;
let day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
          .getDate();
this.datetime = year + "-" + month + "-" + day;  // "2018-03-26"

第四种 字符串拼接方式


function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;

  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }

  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + date.getHours() + seperator2 + date.getMinutes()
    + seperator2 + date.getSeconds();
  return currentdate;
}

var data = getNowFormatDate();
console.log(data);  // 2018-03-26 15:44:5
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值