【JavaScript】Date日期对象的格式化输出及常用日期格式

一般数据库存储的字段都是时间戳,为秒为单位;

     时间戳转换:https://tool.lu/timestamp/

 

一、获取当前时间的时间戳(秒为单位)

var timestamp = Date.parse(new Date()) / 1000;
//当前时间戳为:1562652064
console.log("当前时间戳为:" + timestamp);

二、获取某个时间格式的时间戳

var stringTime = "2019-07-10 10:21:12";
var timestamp2 = Date.parse(new Date(stringTime)) / 1000 ;
//2019-07-10 10:21:12的时间戳为:1562725272
console.log(stringTime + "的时间戳为:" + timestamp2);

三、将当前时间或特定时间戳转换为时间字符串格式

//特定时间戳输出为字符串
var timestamp3 = 1403058804;
var newDate = new Date();
newDate.setTime(timestamp3 * 1000);

//当前时间戳输出为字符串
var nowDate = new Date();

// Wed Jun 18 2014 
console.log(newDate.toDateString());
// Wed, 18 Jun 2014 02:33:24 GMT 
console.log(newDate.toGMTString());
// 2014-06-18T02:33:24.000Z
console.log(newDate.toISOString());
// 2014-06-18T02:33:24.000Z 
console.log(newDate.toJSON());
// 2014年6月18日 
console.log(newDate.toLocaleDateString());
// 2014年6月18日 上午10:33:24 
console.log(newDate.toLocaleString());
// 上午10:33:24 
console.log(newDate.toLocaleTimeString());
// Wed Jun 18 2014 10:33:24 GMT+0800 (中国标准时间)
console.log(newDate.toString());
// 10:33:24 GMT+0800 (中国标准时间) 
console.log(newDate.toTimeString());
// Wed, 18 Jun 2014 02:33:24 GMT
console.log(newDate.toUTCString());

四、自定义格式化输出时间字符串:

//特定时间戳输出为字符串
var timestamp3 = 1403058804;
var newDate = new Date();
newDate.setTime(timestamp3 * 1000);

//当前时间戳输出为字符串
var nowDate = new Date();

newDate.format('yyyy-MM-dd h:m:s')



Date.prototype.format = function(format) {
       var date = {
              "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+)/i.test(format)) {
              format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
       }
       for (var k in date) {
              if (new RegExp("(" + k + ")").test(format)) {
                     format = format.replace(RegExp.$1, RegExp.$1.length == 1
                            ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
              }
       }
       return format;
}

五、日期上下加减不同天数:

     
//天数加减,days传入正负数,月数加减调用setMonth()和getMonth()
function addDate(date,days){ 
    var d=new Date(date); 
    d.setDate(d.getDate()+days); 
    var m=d.getMonth()+1; 
    return d.getFullYear()+'-'+m+'-'+d.getDate(); 
} 

 

你可能感兴趣的:(JavaScript)