在没有插件的情况下,以特定格式在jquery中获取时间戳

Get timestamp in jquery in a particular format without a plugin

本文关键字:格式 定格 jquery 时间戳 获取 插件 情况下      更新时间:2023-09-26

我想在jquery 20140410091906中获得如下时间戳。那是YYYYMMDDHHMMSS格式的。我怎么能在不使用任何插件的情况下做到这一点。

您可以这样做:

new Date().toISOString().replace(/'D/g,"").substr(0,14);

toISOString()year-month-dayThour:minutes:seconds.millisecondsZ格式返回日期。

所以我只是从字符串中删除了TZ-:.,并删除了毫秒。

您可以制作自己的格式,例如:

var myDate = new Date();

因此,如果你想将其显示为mm/dd/yyyy,你可以这样做:

var displayDate = (myDate.getMonth()+1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear();

尝试类似的东西

function lpad(str, len, char) {
    str += '';
    if (str.length >= len) {
        return str;
    }
    return new Array(len - str.length + 1).join(char) + str;
}
function getTs() {
    var date = new Date();
    var str = date.getFullYear() + lpad(date.getMonth(), 2, 0) + lpad(date.getDate(), 2, 0) + lpad(date.getHours(), 2, 0) + lpad(date.getMinutes(), 2, 0) + lpad(date.getSeconds(), 2, 0);
    return str;
}
console.log(getTs())

演示:Fiddle

这样就可以了,

var d= new Date
d.toISOString().replace(/'D+/g,'').substr(0, 14)

Fiddle Demo

Date.prototype.YYYYMMDDHHMMSS = function () {
    var yyyy = this.getFullYear().toString(),
        mm = (this.getMonth() + 1).toString(),
        dd = this.getDate().toString(),
        hh = this.getHours().toString(),
        min = this.getMinutes().toString(),
        ss = this.getSeconds().toString();
    return yyyy + (mm[1] ? mm : "0" + mm[0]) + (dd[1] ? dd : "0" + dd[0]) + (hh[1] ? hh : "0" + hh[0]) + (min[1] ? min : "0" + min[0]) + (ss[1] ? ss : "0" + ss[0]);
};
var d = new Date();
console.log(d.YYYYMMDDHHMMSS());